Node.js 里的this 指向为哪般

108 阅读1分钟

背景:在Node 中的this和 浏览器中的this到底有什么不同呢

首先拆解下从整体全局环境下,其实通过debugg后发现这个是相关this指向其实是一个空对象,这个和global是无关系的。

整体依然遵循浏览器版本this绑定规则,但是又有些不同,显示绑定 --》 隐式绑定 --》new 绑定

首先看一下全局环境里的this 一般打印出来后是一个 {} ,原因node环境下每个模块都是设计为私有的,除非你直接导出 通过module.export 来进行导出。所以其实全局的 this 等价于 module.exports

局部: 主要是函数内部 this 才等价于 global

其余通过显示的绑定或者 new 绑定,箭头函数的this指向规则和浏览器this规则一致

function name1(params) {  
   this.test = 2;  
   // console.log('this2', global.test)  
   console.log('this2', this)  
   console.log('this10', this === global)  
}  
// name()  
let test = {  
   name2: function () {  
       console.log('this3', this)  
   },  
   name3: () => {  
       console.log('this4', this)  
   }  
}  
let test2 = {  
   test3: 2  
}  
console.log('this5', test.name2())  
console.log('this6', test.name3())  
console.log('this7', name1.call(test2, null))  
console.log('this8', new name1())  
console.log('this9', this === module.exports)  
console.log('this11', name1())  

image.png