1
var userData = {
    id: 2,
    name: 'Tim'
}

function Userdata( id, name) {
    this.id = id;
    this.name = name;
    this.getData = () => { 
        console.log('Name: ' + this.name + ' and Id ' + this.id ) 
      }
}

var ud = new Userdata(1, 'Tom');
ud.getData.call(userData);

Output: Name: Tom and Id 1 (why)

I though that ud.getData.call(userData) will set the this to userData when calling function, which is not happening.

repl here

Manasvi Sareen
  • 916
  • 7
  • 17

2 Answers2

4

Arrow functions don't have their own this, they always close over the this where they're defined, and so they'll ignore any this specified by how they're called (whether via call or apply or not).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • So this is kind of a bug fix (on context binding) with es6 new syntax? or other particular reason for it? – Manasvi Sareen Nov 29 '17 at 10:48
  • @ManasviSareen: It's the purpose of arrow functions, to make it easy to create a function that closes over `this` (and `arguments` and `super`) rather than having its own bindings for them. If you don't want that feature, use `function` or method syntax instead. (Method syntax wouldn't apply to your code snippet.) – T.J. Crowder Nov 29 '17 at 10:51
1

Use a regular function:

var userData = {
  id: 2,
  name: 'Tim'
}

function Userdata(id, name) {
  this.id = id;
  this.name = name;
  this.getData = function() {
    console.log('Name: ' + this.name + ' and Id ' + this.id)
  };
}

var ud = new Userdata(1, 'Tom');
ud.getData.call(userData);
André Werlang
  • 5,839
  • 1
  • 35
  • 49