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.Was ist der Ausführungspfad der JavaScript-Engine, wenn my.toString() aufgerufen wird?
認證0級講師
var my=new Triangle(5,10);//[1]
my.getArea();//25 [2]
my.toString();//"Triangle" [3]
[1].創(chuàng)建Triangle實例對象my,
this.name='Triangle';
this.side為 5;
this.height為 10;
[2] 在Triangle實例對象my上調(diào)用方法getArea
[3] 在Triangle實例對象my上調(diào)用方法toString,發(fā)現(xiàn)當前對象上沒有,沿著原型鏈到TwoDShape實例對象上找,還沒有,到Shape實例對象上去找,ok找到。
此時的this對象為Triangle實例對象my,其上的name屬性值為Triangle,輸出
1:先理解好類型和實例的關(guān)系,Shape 是一種類型(抽象),var shape = new Shap(); shape 是一個實例;
2:問題太含糊,var shape = new Shap(); 與 var sh = Shape()的構(gòu)造器的關(guān)系是什么 =》 shape的構(gòu)造函數(shù)就是 Shape.prototype.constructor; (shape和sh怎么會有關(guān)系呢~)
3:為什么不直接繼承?設計如此;
全都拆分開就知道了,首先看new的操作邏輯,TwoDShape.prototype = new Shape();
做了三件事
TwoDShape.prototype = {};
TwoDShape.prototype.__proto__ = Shape.prototype;
Shape.call(TwoDShape.prototype);
同理
Triangle.prototype = {};
Triangle.prototype.__proto__ = TwoDShape.prototype;
TwoDShape.call(Triangle.prototype);
var my = {};
my.__proto__ = Triangle.prototype;
Triangle.call(my, 5, 10);
當執(zhí)行my.toString()
的時候從my
自身成員開始找toString
,沒有就沿著__proto__
往上找,最終在my.__proto__.__proto__
(也就是TwoDShape.prototype
)里找到了toString