在node中,this指向和浏览器稍有不同。下边是我总结的一些内容:
js中声明一个没有var的变量,它会被作为全局对象的属性。
在浏览器中全局对象是window,所以使用window才能访问到:
//在浏览器环境执行 name = 'win' console.log(window.name); //输出win在node中全局对象是global,所以自然就是它的属性咯~
//在node环境执行 name = 'node.js' console.log(global.name); //输出node.js
普通函数的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只是把全局的的名字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。
