10

I am trying to understand arrow functions in ECMAScript 6.

This is the definition I came across while reading:

Arrow functions have implicit this binding, which means that the value of the this value inside of an arrow function is aways the same as the value of this in the scope in which the arrow function is defined!

According to the definition, I believe this for an arrow function should contain the same block level values that the arrow function was defined in.

Code:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: () => console.log(this)
  }
}

console.log(test.k.testfunc);

However, I am getting this result from the code

function testfunc() {
    return console.log(undefined);
}

What I thought I would get would be an output of:

{"laptop": "ramen"}

if I ran this

console.log(test.k.testfunc());

Nate Barbettini
  • 43,095
  • 21
  • 121
  • 135
Liondancer
  • 13,368
  • 38
  • 121
  • 222
  • When using `console.log( test.k.testfunc() );` in FF (note the parentheses at the end), I get a reference to window. Which is correct as when defining the function, the current scope was `window` in my case. – Sirko Jul 27 '15 at 07:47
  • this should help explain: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions "this". See what I did there? – LDJ Jul 27 '15 at 07:48

2 Answers2

5

Let's transform into the equivalent ES5 code:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: function(){return console.log(this)}.bind(this)
  }
}

Remember that this depends on how you call the function. The outer this isn't inside a function, so it will default to undefined in strict mode.

Simplified scenario below:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}
elclanrs
  • 85,039
  • 19
  • 126
  • 159
  • @natebarbettini Arrow functions inherit 'this' from their enclosing scope (function scope), so interestingly, this will work - testfunc: function() { ()=>{console.log(this)}() } – Joe Hanink Dec 31 '15 at 03:35
3

You are defining the arrow function in the same scope that you defined var test. If you are defining test in the global scope, then the arrow function's context will be the global scope too.

If you are defining test inside of a method, the arrow function will share the method's context.

function method() {
  const self = this;

  const test = {
    foo: () => console.log(self === this);
  }

  test.foo()
  // console: true
}
kmiyashiro
  • 2,168
  • 12
  • 15