Skip to content

Instantly share code, notes, and snippets.

@goooooouwa
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goooooouwa/116756b10004dc78419f to your computer and use it in GitHub Desktop.
Save goooooouwa/116756b10004dc78419f to your computer and use it in GitHub Desktop.
Javascript does not have class object, what it has to allow Inheritance is prototype object, which is just another object. The way to create an new object from a prototype object is to define a constructor function for the new object and decorate the prototype property( which is an object) of the constructor function( which is also object in jav…
// 1. define a constructor function for the new object:
var objectConstructor = function(){
this.objAttr = "objAttr";
this.objMethod = function(){
alert("obj method");
}
}
// 2. decorate the prototype property of the constructor function
objectConstructor.prototype.protoAttr = "protoAttr";
objectConstructor.prototype.protoMethod = function(){
alert("proto method");
}
// 3. initiate the new object
object = new objectConstructor();
alert(object.objAttr);
object.objMethod();
alert(object.protoAttr);
object.protoMethod();
// 1. create an parent object from prototype
var parentObjConstructor = function(){
this.parentObjAttr = "parentObjAttr";
};
parentObjConstructor.prototype.parentProtoAttr = "parentProtoAttr";
// 2. create child object which inherit from the parent object
// 2.1 create a constructor function for the child object
var childObjConstructor = function(){
this.childObjAttr = "childObjAttr";
};
// 2.2 assign the parent object to the child object's prototype property
childObjConstructor.prototype = new parentObjConstructor();
// 2.3 decorate the prototype property to extend the parent prototype
childObjConstructor.prototype.childProtoAttr = "childProtoAttr";
// 2.4 initiate the new object
var childObj = new childObjConstructor();
alert(childObj.parentObjAttr);
alert(childObj.parentProtoAttr);
alert(childObj.childObjAttr);
alert(childObj.childProtoAttr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment