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

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

问题描述

我有一个JavaScript文件,由 require 加载。

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"
);

我的问题是:这个 in var a = this; 是一个空对象,而函数中的这个语句是node.js全局对象的阴影。我知道这个关键字在功能上有所不同,但我无法理解为什么第一个这个不等于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 这个,以及它为什么不将它注入模块范围?

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模块中的级别代码,相当于 module.exports 。这是你看到的空对象。

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

当你在一个函数中使用这个时,值为是在该函数的每次执行之前重新确定的,其值为如何执行函数确定。这意味着如果调用机制不同,对完全相同的函数对象的两次调用可能会有不同的值(例如 aFunction() aFunction.call(newThis) emitter.addEventListener(someEvent,aFunction); 等等)在你的情况下,非严格模式下的 aFunction()运行该函数,此设置为全局对象。

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文件 require d作为节点模块时,Node引擎运行模块包装函数内部的代码。使用将设置为 module.exports 来调用该模块包装函数。 (回想一下,上面的函数可以用abitrary 这个值运行。)

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.)

因此,你会得到不同的这个值,因为每个这个都存在于另一个函数中:第一个是在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.

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

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