javascript能不能使用动态原型链?


   
  //基类
  
function Polygon(sides) {
this.sides = sides;
if (typeof Polygon._initialized == “undefined”) {
Polygon.prototype.getArea = function () {
return 0;
};
Polygon._initialized = true;
}
}
//继承类
function Triangle(base, height) {
Polygon.call(this, 3);
this.base = base;
this.height = height;
if (typeof Triangle._initialized == “undefined”) {
Triangle.prototype = new Polygon();//这一行提示有错误,为什么?
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Triangle._initialized = true;
}
}

JavaScript prototype

只是只瓜瓜 12 years, 3 months ago

仔细分析了一下代码,应该把Triangle.prototype = new Polygon();提到外面来

   
  //基类
  
function Polygon(sides) {
this.sides = sides;
if (typeof Polygon._initialized == “undefined”) {
Polygon.prototype.getArea = function () {
return 0;
};
Polygon._initialized = true;
}
}
//继承类
function Triangle(base, height) {
Polygon.call(this, 3);
this.base = base;
this.height = height;
if (typeof Triangle._initialized == “undefined”) {
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Triangle._initialized = true;
}
}

Triangle.prototype = new Polygon();

下面再实例化Triangle。

应该先继承,再实例化!

比如你进行实例化Triangle时候:
var obj = new Triangle(1,3); 这时候只是构造了一个Triangle对象,该函数体并没执行。也就是说obj的prototype值是一个函数对象;当函数执行Triangle()内,你对Triangle.prototype = new Polygon();来改变Triangle.prototype的值。这时候obj已经被实例化了,所以这个语句改变不料它的prototype 。

gldmxcs answered 12 years, 3 months ago

Your Answer