Skip to content

Instantly share code, notes, and snippets.

@sriram15690
Created September 14, 2016 02:51
Show Gist options
  • Save sriram15690/4b11906cba3b6655c9f0e4a935518875 to your computer and use it in GitHub Desktop.
Save sriram15690/4b11906cba3b6655c9f0e4a935518875 to your computer and use it in GitHub Desktop.
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