为什么我不能在Javascript中调用prototyped方法?

时间:2012-09-19 18:23:52

标签: javascript prototype

jsFiddle Demo

我有F继承自Shape。

F.prototype = Shape.prototype;

F使用名称测试创建新方法。

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继承自ShapeTriangle F jsFiddle demo woek well

1 个答案:

答案 0 :(得分:2)

  

我有来自Shape的继承.F

     

F.prototype = Shape.prototype;

严格地说,你不是。您正在覆盖prototype函数的F属性。要构建真正的继承链,您需要使用

F.prototype = Object.create(Shape.prototype);

这样Shape的属性仍可在F实例上使用,但不是相反(因为两个原型都是同一个对象)。所以回答你的第一个问题:是的,你做到了。

另见Why wouldn't I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance?

  

为什么我执行代码警报(B.test());它不起作用?

这很容易解释。 B(你忘了在你的例子中声明,但我们假设它是一个函数)是一个Function对象。您没有分配任何属性。 你所做的是设置它的原型属性(使用new关键字也正确设置原型链,但不小心创建了一个实例 - 首选Object.create。现在,B的任何实例都将从该原型对象继承:

var b = new B();
b.test();
相关问题