node的this和浏览器的this指向的区别

在node中,this指向和浏览器稍有不同。下边是我总结的一些内容:

node的全局对象和浏览器全局对象区别

js中声明一个没有var的变量,它会被作为全局对象的属性。

在浏览器中全局对象是window,所以使用window才能访问到:

//在浏览器环境执行
name = 'win'
console.log(window.name);   //输出win

在node中全局对象是global,所以自然就是它的属性咯~ 

//在node环境执行
name = 'node.js'
console.log(global.name);   //输出node.js

浏览器环境下this普通函数指向

普通函数的this总是指向调用该函数的对象。

最外层的对象就是windows。我们在最外层调用test()函数,所以test()的this也是win,故输出“win”。

//在浏览器执行
window.name = 'win'
function test(){
    console.log(this.name); //输出“win”
}
test();

 并且最外层的this就是windows 

//在浏览器执行
console.log(this === window); //输出“ture”

 所以我们可以写这样一个代码:

//在浏览器执行
this.name = 'win' //这种写法与windows.name=win等价

console.log(this === window); //输出“ture”

function test(){
    console.log(window === this); //输出“true”
    console.log(this.name); //输出“win”
}
test();

好了,以上就是在浏览器中函数指向this简谈。

node环境下this普通函数指向

看懂上边里的例子,我们会认为node只是把全局的的名字window换成了global。

并且看起来也是这样:

//在node环境执行
global.name = 'node.js'
function test(){
    console.log(this.name); //输出“node.js”
}
test();

可是,这不代表node中仅仅是把全局对象改名为global这么简单!

看下边这个例子:

//在node中执行
this.name = 'win' 

console.log(this === global); //输出"false”

function test(){
    console.log(this === global); //输出“true”
    console.log(this.name); //输出“undefined”
}
test();

也就是说,在最外层this不等于global,但是test函数的this依旧指向global。

这是因为在最外层的this并不是全局对象global。而是module.exports

关于module.export具体定义可以查看相关文章,这是es6的新特性。

console.log(module.exports === this); //输出“true”

总结:node中最外层this不等于全局作用域global。而且在最外层调用函数,将会使得函数指向global。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值