3

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?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
acanana
  • 51
  • 7
  • Possible duplicate of [Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)](http://stackoverflow.com/q/27670401/218196) – Felix Kling Dec 21 '16 at 20:20

2 Answers2

6

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");
  });
kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • if that is the case then how to use this in the arrow functions? – Jai Dec 21 '16 at 18:07
  • @Jai well we can use the normal `function(){}`.. enlighten us if there's any other way you know? :) – kukkuz Dec 21 '16 at 18:11
  • 1
    @kukkuz well i was also exploring if there is any way to achieve such thing. – Jai Dec 21 '16 at 18:12
  • @Jai: If you use a function as a callback and the code that calls the callback sets the value of `this` (and you want to use `this`), you can't use an arrow function. Arrow functions do not replace "normal" functions. – Felix Kling Dec 21 '16 at 20:22
2

The other answer is probably the more realistic one, but to note, you could also stop using this and do

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

    // ...
});
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251