前言
最近根据安排,在参与一个自动化测试工具的开发,本项目是基于 Nodejs 开发的,由于挺长时间没有使用 Nodejs 进行完整的项目开发了,所以在开发过程中还会踩不少坑,所以这就来了。
我们这里说的是在 Nodejs 中的 this,而不是在 JavaScript 中的 this。Nodejs 中的 this 和在浏览器中 JavaScript 中的 this 还是不一样的,所以大家还是需要区分一下。(关于 Nodejs 中的 this 与 Javascript 中的 this 的区别,在文末我也替大家总结了一下,记得看哦~)
Nodejs 中 this 的使用
下面,我将分三个部分介绍 this 是如何在 Nodejs 中使用的,它究竟指向的是 WHO??
在全局中的 this
console.log( this ); // {}
this.name = 'Tony';
console.log( this.name ); // Tony
console.log( global.name ); // undefined
全局中的 this 默认是一个空对象,并且在全局中 this
与 global
对象没有任何的关系,那么全局中的 this
究竟指向的是谁呢?想要知道答案,请继续往下看。
在函数中的 this
function fn(){
this.name = 'Tony';
}
fn();
console.log( this ); // {}
console.log( this.name ); // undefined
console.log( global.name ); // Tony
上面的代码可以看出:在函数中 this
指向的是 global
对象,和全局中的 this
不是同一个对象,简单来说,你在函数中通过 this
定义的变量就是相当于给 global
添加了一个属性,此时与全局中的 this
已经没有关系了。
function fn(){
function fn2(){
this.age = 18;
}
fn2();
console.log( this ); // global
console.log( this.age ); // 18
console.log( global.age ); // 18
}
fn();
通过这段代码,可以验证我上面说的:在函数中 this
指向的是 global
对象,和全局中的 this
不是同一个对象。
构造函数中的 this
function Fn(){
this.name = 'Tony';
}
var fn = new Fn();
console.log( fn.name ); // Tony
console.log( global.name ); // undefined
可以看出:在构造函数中 this 指向的是它的实例,而不是全局 global
对象。
回归全局的 this
看完上面这三部分,我们再回过头来看一下全局的 this。说到全局中的 this,其实和 Nodejs 中的作用域有一些关系,如果对 Nodejs 中的作用域问题不太了解,请看下一篇文章:。
this.name = 'Tony';
console.log( module.exports ); // { name: Tony }
console.log( module.exports.name ); // Tony
所以:全局中的 this 指向的是 module.exports
。
怎么样,看完上面三部分,是不是对 Nodejs 的 this 又有了新的认识呢。
JavaScript 中 this 的使用
由于这一部分内容比较多,就将它单独整理出来了,请小伙伴移步至:浏览器 JavaScript 中的 this 的使用总结【最全总结,值得收藏】
Nodejs 中的 this 与浏览器 JavaScript 中的 this 的区别
上面说好要为大家整理一下 Nodejs 中的 this 与 Javascript 中的 this 的区别,那么,他来了。
希望以上内容可以帮助到大家。有任何问题欢迎讨论留言,不要忘记一键三连哦~。
各位 加油!