Why arrow function is behaving weirdly?

90 views Asked by At

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.

1

There are 1 answers

3
Felix Kling On BEST ANSWER

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