“这个"的含义在 node.js 模块和函数中 [英] Meaning of "this" in node.js modules and functions

查看:25
本文介绍了“这个"的含义在 node.js 模块和函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由 require 加载的 JavaScript 文件.

I have a JavaScript file which is loaded by require.

// loaded by require()

var a = this; // "this" is an empty object
this.anObject = {name:"An object"};

var aFunction = function() {
    var innerThis = this; // "this" is node global object
};

aFunction();

(function(anyParameter){
    console.log(anyParameter.anObject);
})(
    this // "this" is same having anObject. Not "global"
);

我的问题是:this in var a = this; 是一个空对象,而函数中的 this 语句是 node.js 的影子全局对象.我知道 this 关键字在函数中是不同的,但我不明白为什么第一个 this 不等于 global 而 this 在函数中等于 global.

My question is: this in var a = this; is an empty object whereas this statements in functions are shadows of node.js global object. I know this keyword is different in functions but I could not understand why first this is not equal to global and this in functions equals to global.

node.js 如何在函数作用域中将 global 注入到 this 中,为什么不注入到模块作用域中?

How does node.js inject global to this in function scopes, and why it does not inject it to the module scope?

推荐答案

以下是您必须了解的一些基本事实,以澄清情况:

Here's a few fundamental facts you must understand to clarify the situation:

  • 在 Node 模块的顶层代码中,this 等价于 module.exports.这就是你看到的空物体.

  • In the top-level code in a Node module, this is equivalent to module.exports. That's the empty object you see.

当您在函数内部使用 this 时,this 的值会在 每次执行之前重新确定函数,其值是如何确定 函数被执行.这意味着如果调用机制不同(例如 aFunction()aFunction.call(newThis) vs. emitter.addEventListener("someEvent", aFunction);, etc.) 在你的情况下, aFunction() 在非严格模式下运行this 设置为全局对象的函数.

When you use this inside of a function, the value of this is determined anew before each and every execution of the function, and its value is determined by how the function is executed. This means that two invocations of the exact same function object could have different this values if the invocation mechanisms are different (e.g. aFunction() vs. aFunction.call(newThis) vs. emitter.addEventListener("someEvent", aFunction);, etc.) In your case, aFunction() in non-strict mode runs the function with this set to the global object.

当 JavaScript 文件被 required 作为 Node 模块时,Node 引擎会在包装函数内部运行模块代码.该模块包装函数通过设置为 module.exportsthis 调用.(回想一下,上面的函数可以使用任意的 this 值运行.)

When JavaScript files are required as Node modules, the Node engine runs the module code inside of a wrapper function. That module-wrapping function is invoked with a this set to module.exports. (Recall, above, a function may be run with an abitrary this value.)

因此,您会得到不同的 this 值,因为每个 this 驻留在不同的函数中:第一个在 Node 创建的模块包装器函数中,第二个是aFunction 内部.

Thus, you get different this values because each this resides inside a different function: the first is inside of the Node-created module-wrapper function and the second is inside of aFunction.

这篇关于“这个"的含义在 node.js 模块和函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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