箭头函数的这个值 [英] This values for arrow functions

查看:27
本文介绍了箭头函数的这个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 ECMAScript 6 中的箭头函数.

I am trying to understand arrow functions in ECMAScript 6.

这是我在阅读时遇到的定义:

This is the definition I came across while reading:

箭头函数具有隐式的 this 绑定,这意味着箭头函数内的 this 值的值是远离与箭头函数所在作用域中this的值相同已定义!

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!

根据定义,我认为箭头函数this应该包含与定义箭头函数相同的块级值.

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)
  }
}

请记住,this 取决于您调用函数的方式.外部的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆