Last active
August 29, 2015 14:02
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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