Function.prototype.call does not invoke method with provided context

67 Views Asked by At
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

2

There are 2 best solutions below

2
On BEST ANSWER

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).

0
On

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