我有从 Shape 继承的 F。
F.prototype = Shape.prototype;
F 创建名为 test 的新方法。
F.prototype.test = function(){return 'test';};
我知道,如果我编写F.prototype = Shape.prototype;
了我在 F 中创建的所有方法,那么从 Shape 继承的其他类将可以使用这些方法。
我做错了什么?
为什么我在执行代码时会出错alert(B.test());
?
function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};
var F = function(){};
F.prototype = Shape.prototype;
F.prototype.test = function(){return 'test';};
function Triangle(side, height) {
this.side = side;
this.height = height;
}
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
var my = new Triangle(5, 10);
alert(my.toString());
var Second_class = function(){};
Second_class.prototype = Shape.prototype;
B.prototype = new Second_class();
alert(B.test());
在这个例子中,当F
继承自jsFiddleShape
并Triangle
创建自F
jsFiddle 演示 woek 好