![](/img/trans.png)
[英]Explain the output of the following code in JavaScript which seems different from expected
[英]execution of same code in nodeJS gives different output from browser, can one explain
执行这段代码在浏览器中与 nodeJs 不同。
let abc = (() => {
function xyz() {
this.man = "XYZ"
}
xyz();
this.man = "ABC";
})()
console.log(man);
预期的答案是在节点中生成的 XYZ,但在浏览器中找到了 ABC。
首先,有几点:
this
的某些隐式值。 如果你的意思是访问全局object,那么写代码明确引用全局object。strict mode
运行此代码,则此代码将不会运行。 它会抛出异常。 这进一步暗示您不应该编写这样的代码。 此代码取决于this
值的两个默认值。
首先,它取决于this
的顶级值。 在浏览器中,这将是window
object。在 nodejs 模块中,这将是当前模块的module.exports
object。
其次,这取决于this
在您的 function 调用xyz()
中的值。 在浏览器的草率模式下,这将是window
。 在 nodejs 的草率模式下,这将是全局 object。因此, this.man = "XYZ"
在全局 object 上设置一个属性。在严格模式下, xyz()
function 中的this
的值将是undefined
。
第三,您对this.man = "ABC"
的分配取决于 this 在您的顶级箭头 function 定义点的词法值。在浏览器中,它也将是window
。 在 nodejs 中,这将是module.exports
。
因此,在浏览器中,您的xyz()
function 将window.man
设置为"XYZ"
,然后将window.man
设置为"ABC"
。
在 nodejs 中,您的xyz()
function 将global.man
设置为"XYZ"
然后您的箭头 function 将module.exports.man
设置为"ABC"
。
最后,通过插入以下内容以严格模式运行:
"use strict";
作为文件中的第一行代码,你会得到一个错误:
TypeError: Cannot set properties of undefined (setting 'man')
因为xyz()
function this
内部将是undefined
的(应该是)并且尝试在undefined
上设置属性是 TypeError。 您在对象上设置属性。
在严格模式下运行所有代码是个好主意。 该语言中越来越多的功能会自动以严格模式运行,例如 class 方法,因为在严格模式下运行代码会更好。 它不会阻止您做任何没有更好方法的事情。 它只是阻止你做你不应该做的事情(通常是意外的)。
为了在 nodejs 中有一个很好的例子,运行这个:
let abc = (() => {
function xyz() {
this.man = "XYZ"; // sets global.man
}
xyz();
this.man = "ABC"; // sets module.exports.man
})()
console.log(this == module.exports);
console.log(module.exports.man);
console.log(global.man)
你会得到这个 output:
true
ABC
XYZ
这里的另一点是,当您调用 function 例如xyz()
时,执行xyz()
中的 this 的值取决于 function 的调用方式。 您可以在此处查看有关调用 function 的各种方式的说明,以及这如何影响 function 中this
的值。
在草率模式下将它作为普通的 function xyz()
调用会将 function 内的this
的值设置为全局 object。在严格模式下将其作为普通的 function 调用会将 function 内的this
的值设置为undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.