javascriptfunction.prototype

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


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


Solution

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