今天看到一道面试题,是一道关于 this 指向的,觉着挺有价值的,this 的指向在浏览器与 node 中的指向又有区别,而 nodejs 中的 this 又经常会变,其在不同的代码位置中代表不同的涵义,在实际开发中,大家可能也会习惯性写 var self = this 这样的代码,哈哈。本文以此探讨下 this!!

Philadelphia's Magic Gardens. This place was so cool!

# this 的应用场景

  • 全局作用域
  • 函数作用域
  • 在构造函数中

# Node 环境下的全局作用域

console.log(this); //{}
this.name = 'vittore';
console.log(this.name); //vittore
console.log(global.name); //undefined
console.log(module.exports.name); //vittore

可以看到在 Node 环境下,全局中的 this 默认是一个空对象,并且在全局中 this 与 global 对象没有任何的关系,其指向的是 module.exports

# Node 环境下的函数作用域

function fn(){
  this.name = 'vittore';
}
fn();
console.log(this); //{}
console.log(this.name); //undefined
console.log(global.name); //vittore

可以看到在 Node 环境下,函数中 this 指向的是 global 对象,和全局中的 this 不是同一个对象,相当于给 global 添加了一个属性,此时与全局中的 this 已经没有关系了。

# Node 环境下的构造函数

function Fn(){
  this.name = 'vittore';
}
var fn = new Fn();
console.log(fn.name); //vittore
console.log(global.name); //undefined

可以看到在 Node 环境下,构造函数中 this 指向的是它的实例,而不是 global 了。

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Vittore 微信支付

微信支付

Vittore 支付宝

支付宝