// 构造函数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"// 强制使用newfunction 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"
Enforcing new 模式
最新推荐文章于 2024-06-10 21:28:26 发布