箭头功能的值 [英] This values for arrow functions

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

问题描述

我正在尝试了解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 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!

根据定义,我相信这个 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屋!

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