Trip of Javascript OO

Create Object:
function MyObject() {
  this.property = "x";
  this.method = function() {};
}
Useful functions in Object: if(A instanceof Array),  hasOwnProperty('property_name')
Prototype:
x_instance.prototype.new_method = function() {} This line will add new_method to all instances of same class of x_instance. (So. we can use this to monkey patch build-in methods or properties.)
Public and Private properties:
function() {
this.public_property = "x";
var private_property = "y";
this.public_method = function() {}
function private_method() {}
}
Static methods and properties:
function mycircle() { ... }
mycircle.aStaticProperty = true;  // static property
mycircle.aStaticMethod =function () { ... }; // static method
Use anonymous function to make a private scope:
var mycircle = (function () {
var privateStaticVariable = true;
function privateStaticMethod() { ... }
function publicConstructor() {
this.normalInstanceProperty = 1;
...
alert(privateStaticVariable);
};
publicConstructor.prototype.normalProperty = 2;
return publicConstructor;
})();
mycircle.publicStaticProperty = true;
mycircle.publicStaticMethod = function () { ... };
Singletons:
var mySingleton = {a:1, b:2,c:function(){}}
var aReference = mySingleton
Another way: http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html also the way coffee script version: http://coffeescriptcookbook.com/chapters/design_patterns/singleton
var singletonMaker = (function () {
var privateStaticVariable = true;
function privateStaticMethod() { ... }
var onlyInstance;
var returnedObject = {
getInstance: function () {
if( !onlyInstance ) {
onlyInstance = new PrivateConstructor();
onlyInstance.constructor = null; // Then you will never be able to New another this object.
}
return onlyInstance;
}
};
function PrivateConstructor() {}
PrivateConstructor.prototype = returnedObject;
PrivateConstructor.prototype.publicProperty = true;
...
return returnedObject;
})();
...
singletonMaker.foo = true;
var mySingleton = singletonMaker.getInstance();
alert(mySingleton.foo); //true
Sub-classes and class inheritance:
function House() {
this.name = "house"
this.tell_name = function() {
console.log(this.name)
}
}

function Villa(new_name) {
this.name = new_name || this.name
}

// Method 1: Villa.prototype.__proto__ = House.prototype; // this is another way.
// Method 2: Villa.prototype = House.prototype;
// Method 3: 
// function Villa() {
//   House.apply(this, arguments);
// }
// Method 4:
Villa.prototype = new House()
Villa.prototype.constructor = Villa
Villa.prototype.show_swimming_pool = function() {
  console.log("swimming pool")
}
v = new Villa("villa")
v.tell_name()
v.show_swimming_pool()
Javascript Objects Map: http://www.howtocreate.co.uk/tutorials/javascript/javascriptobject
blog comments powered by Disqus