为什么我不能在Javascript中调用prototyped方法? [英] Why can't I call a prototyped method in Javascript?
问题描述
我有F继承自Shape。
I have F which inherits from Shape.
F.prototype = Shape.prototype;
F使用名称测试创建新方法。
F creates new method with name test.
F.prototype.test = function(){return 'test';};
我明白如果我写 F.prototype = Shape.prototype;
我在F中创建的所有方法都可以从继承自Shape的其他类中获得。
I understand that if I write F.prototype = Shape.prototype;
all the methods which I create in F will be available by other class which inheritance from 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
继承自 Shape
和 Triangle
从 F
<创建a href =http://jsfiddle.net/centerwow/nHetS/1/ =nofollow> jsFiddle demo woek well
in this example when F
which inherits from Shape
and Triangle
created from F
jsFiddle demo woek well
推荐答案
我有从F继承的F。
I have F which inheritance from Shape.
F.prototype = Shape。原型;
严格来说,你不是。您正在覆盖 F
函数的 prototype
属性。要构建一个真正的继承链,你需要使用
Strictly speaking, you're not. You are overwriting the prototype
property of the F
function. To build a real inheritance chain, you would need to use
F.prototype = Object.create(Shape.prototype);
因此Shape的属性仍可在F实例上使用,但不是相反的方式(因为两个原型)是同一个对象)。所以回答你的第一个问题:是的,你做了。
so that Shape's properties are still available on F instances, but not the other way round (as both prototypes were the same object). So to answer your first question: Yes, you did.
另见为什么我不会使用Child.prototype = Parent.Prototype而不是Child.prototype = new Parent();对于Javascript继承?
为什么我执行代码警报(B.test());它不起作用?
why when I execution the code alert(B.test()); it is not working ?
这很容易解释。 B
(你忘了在你的例子中声明,但我们假设它是一个函数)是一个Function对象。您没有分配任何属性。
您所做的是设置它的原型属性(使用 new
关键字也正确设置原型链,但不小心创建了一个实例 - Object.create
是首选)。现在, B
的任何实例将从该原型对象继承:
That's simple to explain. B
(which you forgot to declare in your example, but let's assume it's a function) is a Function object. You don't have any properties assigned to it.
What you have done is setting it's prototype property (using the new
keyword also sets up the prototype chain correctly, but accidentally creates an instance - Object.create
is preferred). So now, any instances of B
will inherit from that prototype object:
var b = new B();
b.test();
这篇关于为什么我不能在Javascript中调用prototyped方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!