Node.js:在模块范围中使用``this`运算符的上下文是什么? [英] Node.js: What is the context of the `this` operator when used in module scope?

查看:114
本文介绍了Node.js:在模块范围中使用``this`运算符的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写下面的代码并将其保存为test.js:

  var foo ='我是本地的'; 
global.foo ='我是全球性的';

函数print(){
console.log(this.foo);
};

print();
console.log(this.foo);

然后,我使用命令 node test.js 并返回:

 我是全球性的
undefined


问题



为什么它不返回:

 我是全球性的
我是全球性的
$ b

解决方案

在Node模块中, by design指模块的出口对象:

  console.log(this === exports); // true 

制作 console.log(this.foo)相当于 console.log(exports.foo)



换句话说, code> this 引用全局对象,本地变量也奇迹般地成为 exports 的属性。



因为 exports.foo 不存在,所以您得到 undefined


The code

I write the following code and save it as test.js:

var foo = 'I am local';
global.foo = 'I am global';

function print () {
     console.log(this.foo);
};

print(); 
console.log (this.foo); 

I then run it in the terminal with the command node test.js and it returns:

I am global
undefined

The question

Why does it not return:

I am global
I am global

?

解决方案

Inside a Node module, this by design refers to module's exports object:

console.log(this === exports); // true

Making console.log(this.foo) equivalent to console.log(exports.foo).

In other words, neither does this refer to the global object nor do local variables magically become properties of exports.

Since exports.foo doesn't exist, you get undefined.

这篇关于Node.js:在模块范围中使用``this`运算符的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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