Lio*_*cer 9 javascript ecmascript-6 arrow-functions
我想了解ECMAScript 6中的箭头功能.
这是我在阅读时遇到的定义:
箭头函数具有隐式
this
绑定,这意味着this
箭头函数内部值的值与this
定义箭头函数的范围中的值相同!
根据定义,我相信this
一个arrow function
应该包含箭头函数定义的相同块级别值.
码:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: () => console.log(this)
}
}
console.log(test.k.testfunc);
Run Code Online (Sandbox Code Playgroud)
但是,我从代码中得到了这个结果
function testfunc() {
return console.log(undefined);
}
Run Code Online (Sandbox Code Playgroud)
我以为我会得到的输出是:
{"laptop": "ramen"}
Run Code Online (Sandbox Code Playgroud)
如果我跑了
console.log(test.k.testfunc());
让我们转换成等效的 ES5 代码:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: function(){return console.log(this)}.bind(this)
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,这this
取决于您如何调用该函数。外部this
不在函数内部,因此默认为undefined
严格模式。
简化场景如下:
console.log(this) // undefined
var test = {
a: this // same `this` as above
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
285 次 |
最近记录: |