箭头功能的值 [英] This values for arrow functions
问题描述
我正在尝试了解ECMAScript 6中的箭头功能。
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 thethis
value inside of an arrow function is aways the same as the value ofthis
in the scope in which the arrow function is defined!
根据定义,我相信这个
code> arrow函数应该包含相同的块级别值,用于定义箭头函数。
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.
代码:
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"}
如果我运行这个
console.log(test.k.testfunc());
推荐答案
让我们转换成等效的ES5代码:
Let's transform into the equivalent ES5 code:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: function(){return console.log(this)}.bind(this)
}
}
<请记住,这个
取决于如何调用该功能。外部这个
不在一个函数内,所以它将在严格模式下默认为 undefined
。
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.
下面的简化方案:
console.log(this) // undefined
var test = {
a: this // same `this` as above
}
这篇关于箭头功能的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!