JavaScript Patterns 5.7 Object Constants】的更多相关文章

Principle Make variables shouldn't be changed stand out using all caps. Add constants as static properties to the constructor function. // constructor var Widget = function () { // implementation... }; // constants Widget.MAX_HEIGHT = 320; Widget.MAX…
Basic concept Values can be properties: primitives or other objects methods: functions User-defined native objects are mutable at any time. Object literal notation is ideal for this type of on-demand object creation. Even the simplest {} object alrea…
7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =…
Scenario You want to use just the methods you like, without inheriting all the other methods that you’ll never need. This is possible with the borrowing methods pattern, which benefits from the function methods  call() and apply(). // call() example…
Loop through arguments and copy every property of every object passed to the function. And the result will be a new object that has the properties of all the source objects. function mix() { var arg, prop, child = {}; for (arg = 0; arg < arguments.le…
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { child[i] = parent[i]; } } return child; } Deep copy pattern function extendDeep(parent, child) { var i, toStr = Obje…
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function  F().  Set the prototype of  F() to be the parent object. Return a new instance of the temporary constructor. function Object(o) { function F() {} F.…
Commonalities • There’s a convention on how to name a method, which is to be considered the constructor of the class. • Classes inherit from other classes. • There’s access to the parent class (superclass) from within the child class. The function ta…
// the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functionality to the prototype Parent.prototype.say = function () { return this.name; }; // empty child constructor function Child(name) {} inherit(Child, Paren…
Chaining Pattern - Call methods on an object one after the other without assigning the return values of the previous operations to variables and without having to split your calls on multiple lines. var obj = { value: 1, increment: function () { this…