Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This values for arrow functions [duplicate]

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());

like image 495
Liondancer Avatar asked Jul 27 '15 07:07

Liondancer


People also ask

What is the value of this in arrow function?

In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What are the disadvantages of arrow function?

An Arrow function should not be used as methods. An arrow function can not be used as constructors. An arrow function can not use yield within its body. Arrow function cannot be suitable for call apply and bind methods.

Which of the following about arrow function is incorrect?

An Arrow function can not be used as a constructor. Usage of yield expression is not allowed in Arrow functions. That means an Arrow function can not be a generator. In an Arrow function the this is already bound or captured from enclosing context.


1 Answers

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
}
like image 151
elclanrs Avatar answered Nov 05 '22 11:11

elclanrs