Mar*_*tus 5 javascript this node.js
根据MDN的这个解释:
this指的是全局对象然而,以下内容:
var globalThis = this;
function a() {
console.log(typeof this);
console.log(typeof globalThis);
console.log('is this the global object? '+(globalThis===this));
}
a();
Run Code Online (Sandbox Code Playgroud)
...放在文件中foo.js产生:
$ nodejs foo.js
object
object
is this the global object? false
Run Code Online (Sandbox Code Playgroud)
在Node.js中,我们在模块中编写的任何代码都将包含在函数中.在这个详细的答案中,您可以阅读更多相关信息.因此,this在模块的顶层将引用该函数的上下文,而不是全局对象.
您实际上可以使用globalobject来引用实际的全局对象,就像这样
function a() {
console.log('is this the global object? ' + (global === this));
}
a();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
488 次 |
| 最近记录: |