Enforcing new 模式

 
  
// 构造函数
function Waffle () {
this . tastes = "yummy" ;
}
// 反例
// 忘记使用 `new`
var good_morning = Waffle ();
console . log ( typeof good_morning ); // "undefined"
console . log ( window . tastes ); // "yummy" 此时 构造函数Waffle中的this指代window
//更改为使用new关键字
var good_morning = new Waffle ();
console . log ( typeof good_morning ); // "object"
console . log ( good_morning . tastes ); // "yummy"
// 强制使用new
function Waffle () {
if ( ! ( this instanceof Waffle )) {
return new Waffle ();
}
this . tastes = "yummy" ;
}
var good_morning = new Waffle ();
var good_evening = Waffle ();
console . log ( typeof good_morning ); // "object"
console . log ( good_morning . tastes ); // "yummy"
console . log ( typeof good_evening ); // "object"
console . log ( good_evening . tastes ); // "yummy"

你可能感兴趣的:(javascript)