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?
認(rèn)證0級(jí)講師
var my=new Triangle(5,10);//[1]
my.getArea();//25 [2]
my.toString();//"Triangle" [3]
[1]. Create Triangle instance object my,
this.name='Triangle';
this.side為 5;
this.height為 10;
[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 things
TwoDShape.prototype = {};
TwoDShape.prototype.__proto__ = Shape.prototype;
Shape.call(TwoDShape.prototype);
Same reason
Triangle.prototype = {};
Triangle.prototype.__proto__ = TwoDShape.prototype;
TwoDShape.call(Triangle.prototype);
var my = {};
my.__proto__ = Triangle.prototype;
Triangle.call(my, 5, 10);
When executing my.toString()
, start looking for toString
from my
's own members. If not, search up along __proto__
, and finally find my.__proto__.__proto__
(that is, TwoDShape. Found
toString in prototype