JavaScript Patterns 2.9 Coding Conventions】的更多相关文章

It’s important to establish and follow coding conventions—they make your code consistent, predictable, and much easier to read and understand. A new developer joining the team can read through the conventions and be productive much sooner, understand…
1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the words in lowercase, only capitalizing the first letter in each word. upper camel case, as in  MyConstructor(), lower  camel  case,  as  in  myFunction(),…
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…
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.…
// 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…
In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var adam = new Person(); JavaScript’s constructor invocation looks as if Person were a class, but it’s important to keep in mind that Person is still just a…