搜尋

首頁  >  問答  >  主體

javascript - 關於繼承的問題

function extend(Child,Parent){
var F=function(){};
F.prototype=Parent.prototype;
Child.prototype=new F();
Child.prototype.constructor=Child;
Child.uber=Parent.prototype;
}

function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function(){
return this.constructor.uber
    ?this.constructor.uber.toString()+', ' + this.name
    :this.name;
};

function TwoDShape(){}
extend(TwoDShape,Shape);
TwoDShape.prototype.name='2D shape';

function Triangle(side,height){
this.side=side;
this.height=height;
}

var F=function(){};
extend(Triangle,TwoDShape);
Triangle.prototype.name='Triangle';
Triangle.prototype.getArea=function(){
return this.side*this.height/2;
};

var Shape=function(){};
var TwoDShape=function(){};
Shape.prototype.name='shape';
Shape.prototype.toString=function(){
return this.uber
?this.uber.toString()+', ' + this.name
:this.name;
};

extend(TwoDShape,Shape);    
var td=new TwoDShape();

td.name;//"shape"

1.為什麼說name屬性既不會是TwoDShape()實例的屬性,也不會成為其原型物件的屬性,但是子物件依然可以透過繼承方式來存取該屬性?

PHP中文网PHP中文网2804 天前606

全部回覆(2)我來回復

  • 滿天的星座

    滿天的星座2017-06-15 09:23:31

    因為子物件繼承的是一整條原型鏈,而不是單一原型

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-15 09:23:31

    掛載在原型鏈上的屬性當然不是

    回覆
    0
  • 取消回覆