1

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.

SomeDevloperName
  • 462
  • 1
  • 4
  • 9
  • For a good explanation, have a look at this too: http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan Jan 02 '17 at 08:57

1 Answers1

4

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

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • 1
    I don't know. I felt like it was worth talking about this specific example. But I don't don't have a strong opinion about it. – Felix Kling Jan 02 '17 at 07:49
  • 1
    @mplungjan I read that question before but I think this was some specific example. Even you can assign variable to arrow function and this will always point to original object only. This was something new and so I think duplicate is not appropriate. – SomeDevloperName Jan 02 '17 at 08:01
  • Reopened and linked to http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6 – mplungjan Jan 02 '17 at 08:58