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.
Inside an arrow function,
this
is resolved lexically, basically like any other variable, e.g. likename
. It doesn't matter how the function is called, itsthis
value will be determined when the function is created.Therefore,
this
insidebar.showName
will always refer to the instance created bynew 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? .