Search code examples
javascriptjquerynode.jsecmascript-6browserify

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


I created the following NodeJs module :

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");
  });
}

and my Browserify entry point looks like this:

"use strict";

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

test();

When I click on the element, the click event is triggered, but $(this) is undefined. Here's the result of different 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

Any idea why?


Solution

  • Arrow functions do not bind its own this argument - that is why you get undefined - so you can use the normal function mode:

    $("#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");
      });