如果有时候我们忘记对构造函数使用new的话,构造函数的this将指向window

function Person(){
  this.name = 'Julie';
}
var good_moring = Person();
console.log(good_moring); //输出undefined
console.log(window.name); //输出Julie

 

遵循命名约定一定程序上有助于避免忘记使用new所带来的问题,但命名约定也只是一种建议,并不能强制保证正确的行为。

板栗:

function Waffle(){
  if( !(this instanceof Waffle) ){
    return new Waffle();
  }
  this.name = 'carl';
}
var first = new Waffle(),
second = Waffle();
console.log(first.name); //carl
console.log(second.name); //carl

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2021-09-12
  • 2021-09-06
  • 2021-08-14
  • 2021-09-18
  • 2022-12-23
猜你喜欢
  • 2021-08-27
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案