2016-12-21 76 views
1

我創建了以下NodeJs模塊的NodeJS模塊上的 「不確定」:

import $ from 'jquery'; 

module.exports =() => { 

    $("#clients-table tbody tr").click(() => { 

    let $this = $(this); 

    console.log($this); 
    console.log($(this)); 
    console.log($(this).attr("class")); 
    console.log($("#clients-table tbody tr").attr("class")); 
    console.log("end"); 
    }); 
} 

和我Browserify入口點看起來是這樣的:

"use strict"; 

import $ from 'jquery'; 
import test from './test'; 

test(); 

當我點擊元素時,點擊事件被觸發,但$(this)undefined。 這裏有不同的console.logs結果:

test.js:9 he.fn.init {} 
test.js:10 he.fn.init {} 
test.js:11 undefined 
test.js:12 test 
test.js:13 end 

任何想法,爲什麼?

+0

[用ES6箭頭功能使用jQuery $(本)(詞法此綁定)的可能的複製(HTTP:// stackov erflow.com/q/27670401/218196) –

回答

2

Arrow functions綁定自己的this的說法 - 這就是爲什麼你undefined - 這樣你就可以使用正常的功能模式:

$("#clients-table tbody tr").click(function() { 

    let $this = $(this); 

    console.log($this); 
    console.log($(this)); 
    console.log($(this).attr("class")); 
    console.log($("#clients-table tbody tr").attr("class")); 
    console.log("end"); 
    }); 
+0

如果是這樣的話那麼如何在箭頭函數中使用這個? – Jai

+0

謝謝!並感謝鏈接! – acanana

+0

@Jai我們可以使用普通的'function(){}'..如果還有其他的方法可以啓發我們嗎? :) – kukkuz

2

對方回答可能是更現實的,但注意,你也可以停止使用this並做

$("#clients-table tbody tr").click(evt => { 
    let $this = $(evt.currentTarget); 

    // ... 
}); 
+0

有趣,謝謝你的建議! – acanana