为什么Chrome无法(或CAN)在ES6的Arrow功能中找到上下文

问题描述:

[更新]:原来有两个原因要问我:

对于不能 :我缺乏关于箭头功能如何工作的知识,它只是将周围的上下文锁定在它定义的任何地方。在严格模式下,全局变量为未定义

For CAN NOT: It is my lack of knowledge about how arrow function works, it just locks the surrounding context everywhere it defined. And the global is undefined in strict mode.

对于 CAN :可能是

请参阅注释以了解什么是 CAN CAN NOT 这里

Please refer to comment to find out what are the CAN and CAN NOT here

全部:

我很新到ES6,当我尝试使用箭头函数的词法上下文锁定概念时,我使用的代码如下:

I am pretty new to ES6, when I try arrow function's concept of lexical context locking, I use code like:

var glb = {name: "glb" };
glb.showname = () => {
    /******* interesting thing happens here below *******/
    console.log(this);
    this.name = "hello"
    return () => {
        console.log(this.name);
    }
}
const ext = {name: "ext"};
ext.showname = glb.showname();
ext.showname();

然后我将其转换为:

browserify main.js  -o bundle.js -t [ babelify --presets [ es2015 ]   ] -d

有趣的是:

当我在不设置断点的情况下运行它时(无论是使用Node还是在Chrome中),它总是给我错误:

When I run it without setting breaking point(either with Node or in Chrome), it always give me error:


未捕获的类型错误:无法设置未定义的属性'name'

Uncaught TypeError: Cannot set property 'name' of undefined

,控制台只打印出 undefined

断点(我在Chrome中做到),这一次,上下文可以像这样打印出来

 Object {name: "glb"}

为什么会这样?

谢谢

如果Chrome开发工具正在报告 this 变为 glb ,那么工具中就有一个错误,这不足为奇n新箭头功能如何。如您的错误所述,应该等于未定义

If the Chrome dev tools are reporting this to be glb then there is a bug in the tools, which isn't too surprising given how new arrow functions are. this should be equal to undefined, as stated in your error.

箭头函数绑定到它们的词法范围,也只有它们的词法范围。意思是,无论函数附加到哪个对象,都将始终使用原始词法范围来调用它。这段代码显示了箭头功能如何工作的一些示例。

Arrow functions bind to their lexical scope and only their lexical scope. Meaning, regardless of what object the function is attached to, it will always be called with the original lexical scope. This code shows a few examples of how arrow functions work.

var globalScope = () => {
  console.log(this); // undefined
};

function MyObj() { // Assuming we use it as a constructor
  console.log(this); // MyObj
  this.myObjScope = () => {
    console.log(this); // MyObj
  };
}

MyObj.prototype.globalScope = () => {
  console.log(this); // undefined
};

有关箭头功能的详细说明,请参见此堆栈溢出答案。

For a detailed rundown on arrow functions, see this Stack Overflow answer.