jQuery $(this) 在 nodejs 模块上是 "undefined"(使用 Browserify)

jQuery $(this) is "undefined" on a nodejs module (using Browserify)

我创建了以下 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

知道为什么吗?

Arrow functions do not bind its own this argument - 这就是你得到 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");
  });

另一个答案可能更现实,但请注意,您也可以停止使用 this 并执行

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

    // ...
});