0

I very confusing about the value of this at the moment of an invocation function using arrow functions. Let's take my example:

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

When i put this code on the browser console, an interesting thing happens, func1() will output 5 as expected *, but when i run func2 i got undefined. What is going on here? Why the value of this inside func2 makes reference to the global object(Window in this case).

I think i expect that output, because it is how it works, thats the reason why Alan and slevetman explains here and here respectively. But according to the Jason's explanation

Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.

So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?

Community
  • 1
  • 1
Vercryger
  • 560
  • 6
  • 17
  • It seems you understand how `this` behaves differently in arrow functions, but you don't understand how `this` behaves in general. – Oriol Jul 24 '16 at 23:30

2 Answers2

3

So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?

The obj here is not the "enclosing" scope. The scope that you are defining the obj in is the "enclosing" scope.

Consider this example:

var obj = {
  property: 5,
  func1: function () {
      let func2 = () => {
        console.log(this.property); 
      }
      func2();
  },
}
obj.func1(); // logs 5
obj.func1.call({
   property: 6
}) // logs 6

When the inner func2 is called, the this keyword refers to the obj as this in the wrapper func1 function refers to the obj and the func2 inherits the this value. The inner arrow function does not bind it's own this value.

undefined
  • 136,817
  • 15
  • 158
  • 186
  • What you are trying to tell me is that the enclosing scope of the function is `Window`? – Vercryger Jul 24 '16 at 23:22
  • 1
    @Vohuman Curious why using `Function.prototype.call()` does not set `this` to `obj` at `obj.func2.call(obj)`? https://jsfiddle.net/pje0dtgn/ – guest271314 Jul 24 '16 at 23:23
  • @Vohuman http://stackoverflow.com/questions/38557902/function-prototype-call-does-not-set-this-at-arrow-function – guest271314 Jul 24 '16 at 23:38
-1

The this in func2 is inheriting the value of the scope of the function itself, no more. To make it work, you'll have to make something like that :

var obj = {
    property: 5,
    func1: function () {
        console.log(this.property); // shows 5
    },
    func2: () => {
        console.log(this.property); // shows undefined
        this.property = 6;
        console.log(this.property); // shows 6
    }
}
Odonno
  • 379
  • 2
  • 5