Object Oriented Javascript
Object Oriented Javascript
Methods are owned by the objects they're assigned to this refers to function's owner
Copying / assigning a function to an object changes this apply/call apply the function as the method of the object passed as first argument this is passed as first argument BIND: objects and bound methods / cooks and their cookbooks JavaScript pseudo-classes: Constructor functions and Prototype objects
Constructors
Prototypes
All constructors have a prototype property prototype has a property named constructor
All objects inherit properties from their prototype
All objects (with the same constructor) share the same instance of their prototype
Inherited properties are not copied to the new object, they are references to the prototype properties => decreased memory usage + changes reflected in all instances Distinguish inherited properties with .hasOwnProperty() method Writing to an inherited property creates a local copy
String.prototype.trim = function () {
return this.replace(/(^\s+)|(\s+$)/,'');
};
Array.prototype.map
Useful for cross-browser compatibility Do NOT add properties to Object.prototype window, document and other host objects do not have prototype and nor can be extended
Constructor
Instance properties and methods
this is not implicitly included in the scope Class properties and methods Private properties / data encapsulation using closures
this.getRadius = function () { return r; };
function Circle(r) { }
CustomString.prototype.constructor = CustomString;
function CustomString (v) { String.call(this, v); } CustomString.prototype.superclass = String; function CustomString (v) { this.superclass(v); }
Overridden methods
Extention Utilities
Subclasses can borrow properties from superclasses by copying them from one prototype to another Mixins: collections of generic properties to be borrowed instanceof, constructor, Object.prototype.toString and duck typing Building a framework with utilities to declare, inherit, extend pseudo-classes
Prevent definitions clashes by defining modules and namespaces Namespaces generally defined as objects
Recap
Constructor
Prototype
Inheritance