JavaScript Patterns 3.3 Patterns for Enforcing new

王朝学院·作者佚名  2016-05-23
窄屏简体版  字體: 小  |  中  |  大  |  超大  

javaScript Patterns 3.3 Patterns for Enforcing new 2014-05-29 13:24 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑 When your constructor has something like this.member and you invoke the constructor without new, you’re actually creating a new PRoperty of the global object called member and accessible through window.member or simply member.

// constructorfunction Waffle() { this.tastes = "yummy";}// a new objectvar good_morning = new Waffle();console.log(typeof good_morning); // "object"console.log(good_morning.tastes); // "yummy"// antipattern:// forgotten `new`var good_morning = Waffle();console.log(typeof good_morning); // "undefined"console.log(window.tastes); // "yummy"

This undesired behavior is addressed in ECMAScript 5, and in strict mode this will no longer point to the global object. If ES5 is not available, there’s still something you can do to make sure that a constructor function always behaves like one even if called without new.

Naming Convention

uppercase the first letter in constructor names (MyConstructor) and lowercase it in “normal” functions and methods (myFunction).

Using that

function Waffle() { var that = {}; that.tastes = "yummy"; return that;} function Waffle() { return { tastes: "yummy" };} var first = new Waffle(), second = Waffle();console.log(first.tastes); // "yummy"console.log(second.tastes); // "yummy"

Disadvantage

The link to the prototype is lost, so any members you add to the Waffle()prototype will not be available to the objects.

Self-Invoking Constructor

In the constructor you check whether this is an instance of your constructor, and if not, the constructor invokes itself again, this time properly with new:

function Waffle() { if (!(this instanceof Waffle)) { return new Waffle(); } this.tastes = "yummy";}Waffle.prototype.wantAnother = true;// testing invocationsvar first = new Waffle(),second = Waffle();console.log(first.tastes); // "yummy"console.log(second.tastes); // "yummy"console.log(first.wantAnother); // trueconsole.log(second.wantAnother); // true

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航