关于继承的问题

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()实例的属性,也不会成为其原型对象的属性,但是子对象依然可以通过继承方式来访问该属性?

阅读 2.7k
3 个回答

TwoDShapes实例上没有name属性,其原型对象也就是Shape实例对象上也没有这个属性,
但是Shape的原型对象上有这个属性name;

var td=new TwoDShape();
td.name;//"shape"
console.log(td.hasOwnProperty("name"));//false
console.log(td.__proto__.hasOwnProperty("name"));//false
console.log(td.__proto__.__proto__.hasOwnProperty("name"));//true

因为子对象继承的是一整条原型链,而不是单个原型

挂载在原型链上的属性当然不是

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题