SomeDevloperName
SomeDevloperName

Reputation: 630

Why arrow function is behaving weirdly?

Consider the following code:

function Person (name) {
    this.name = name;
    this.showName = function() { console.log(name, this.name);}
}

var foo = new Person('foo');

var bar = new Person('bar');

foo.showName = bar.showName;

foo.showName(); // prints "bar foo"

It is expected as this still binds "foo".

Now with arrow functions:

function Person (name) {
    this.name = name;
    this.showName = () => console.log(name, this.name);
}

var foo = new Person('foo');

var bar = new Person('bar');

foo.showName = bar.showName;

foo.showName(); // prints "bar bar"

I know that 'this' doesn't bind to arrow functions. But here context of "foo" has changed in showName(). This itself removes the one use-case of "bind" function. What is the reason behind it.

Upvotes: 0

Views: 84

Answers (1)

Felix Kling
Felix Kling

Reputation: 816394

Inside an arrow function, this is resolved lexically, basically like any other variable, e.g. like name. It doesn't matter how the function is called, its this value will be determined when the function is created.

Therefore, this inside bar.showName will always refer to the instance created by new Person('bar').


See also What does "this" refer to in arrow functions in ES6? and Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? .

Upvotes: 3

Related Questions