Created
September 14, 2016 02:51
-
-
Save sriram15690/4b11906cba3b6655c9f0e4a935518875 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function Shape(){ | |
this.name = 'Shape'; | |
this.toString = function () { | |
return this.name; | |
}; | |
} | |
function TwoDShape(){ | |
this.name = '2D shape'; | |
} | |
function Triangle(side, height){ | |
this.name = 'Triangle'; | |
this.side = side; | |
this.height = height; | |
this.getArea = function () { | |
return this.side * this.height / 2; | |
}; | |
} | |
TwoDShape.prototype = new Shape(); | |
Triangle.prototype = new TwoDShape(); | |
TwoDShape.prototype.constructor = | |
TwoDShape; | |
Triangle.prototype.constructor = | |
Triangle; | |
var my = new Triangle(5, 10); | |
alert(my.getArea()) ;// 25 | |
alert(my.toString()) ;// triangle | |
alert(my.constructor === Triangle); | |
alert(my instanceof Shape); // true | |
alert(my instanceofTwoDShape);// true | |
alert(my instanceof Triangle);// true | |
alert(my instanceof Array); // false | |
alert(Shape.prototype.isPrototypeOf(my));//true | |
alert(TwoDShape.prototype.isPrototypeOf(my));//true | |
alert(Triangle.prototype.isPrototypeOf(my));//true | |
alert(String.prototype.isPrototypeOf(my));//false | |
// Note:-It's fascinating to consider what the JavaScript engine does | |
when you call my.toString(): | |
ï It loops through all of the properties of my and | |
doesn't find a method called toString(). | |
ï It looks at the object that my.__proto__ points to; | |
this object is the instance new TwoDShape() created | |
during the inheritance process. | |
ï Now, the JavaScript engine loops through the instance | |
of TwoDShape and doesn't find a toString() | |
method. It then checks the __proto__ of that object. | |
This time __proto__ points to the instance | |
created by new Shape(). | |
ï The instance of new Shape() is examined and | |
toString() is finally found. | |
ï This method is invoked in the context of my, meaning | |
that this points to my. | |
//----------------------------------------------------- | |
// You can seperate object using other two constructors | |
//----------------------------------------------------- | |
var td = new TwoDShape(); | |
>td.constructor === TwoDShape; | |
true | |
>td.toString(); | |
"2D shape" | |
>var s = new Shape(); | |
>s.constructor === Shape; | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment