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();
var my=new Triangle(5,10);
my.getArea();//25
my.toString();//"Triangle"
1.When my.toString() is called, what is the execution path of the JavaScript engine?
[1]. Create Triangle instance object my,
[2] Call the method getArea on the Triangle instance object my
[3] Call the method toString on the Triangle instance object my and find that it does not exist on the current object. Follow the prototype chain to find the TwoDShape instance object. If it does not exist yet, go to the Shape instance. Go up and look for the object, OK, find it.
The this object at this time is the Triangle instance object my, the name attribute value on it is Triangle, and the output is
1: First understand the relationship between types and instances. Shape is a type (abstract), var shape = new Shap(); shape is an instance;
2: The question is too vague, var shape = new Shap(); and What is the relationship between the constructor of var sh = Shape() => The constructor of shape is Shape.prototype.constructor; (How can shape and sh be related~)
3: Why not inherit directly? Designed like this;
You can see it by splitting it all. First, look at the operation logic of new,
TwoDShape.prototype = new Shape();
It does three thingsSame reason
When executing
)my.toString()
, start looking fortoString
frommy
's own members. If not, search up along__proto__
, and finally findmy.__proto__.__proto__
(that is,TwoDShape. Found
toStringin prototype