When you invoke the constructor function with new, the following happens inside the function: • An empty object is created and referenced by this variable, inheriting the prototype of the function. • Properties and methods are added to the object ref…
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 =…
Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s global. In the namespacing pattern, there is no way to have two versions of the same application or library run on the same page, because they both ne…
All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return this.myprop; } }; console.log(myobj.myprop); // `myprop` is publicly accessible console.log(myobj.getProp()); // getProp() is public too The same is…
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…
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…
Advantage Avoid re-created instance method to this inside of the constructor. method() implementation The method() takes two parameters: • The name of the new method • The implementation of the method if (typeof Function.prototype.method !== "functio…