Javascript 原型继承的怪异
我正在尝试完成一些 javascript 继承示例,但我遇到了这个问题:
function Animal(){}
Animal.prototype.type = "animal";
Animal.prototype.speak = function(){ console.log( "I'm a " + this.type +
". I can't really talk ;)" ); }
function Dog(){}
function F(){}
F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;
Dog.prototype.type = "Dog";
Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }
var rover = new Dog();
rover.woof();
我得到了这个,但我不知道为什么:
TypeError: Object #<Dog> has no method 'woof'
我知道我可以将未找到的方法放入构造函数中,但我正在尝试通过原型修改来做到这一点。我在这里做错了什么?
I'm trying to work through some javascript inheritance examples and I hit a wall with this one:
function Animal(){}
Animal.prototype.type = "animal";
Animal.prototype.speak = function(){ console.log( "I'm a " + this.type +
". I can't really talk ;)" ); }
function Dog(){}
function F(){}
F.prototype = Animal.prototype;
Dog.prototype = new F();
Dog.prototype.constructor = Dog;
Dog.prototype.type = "Dog";
Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }
var rover = new Dog();
rover.woof();
I am getting this and I have no idea why:
TypeError: Object #<Dog> has no method 'woof'
I know I can put the not-found method into the constructor function, but I am trying to do this with prototype modification. What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更改:
至:
Change:
To:
Dog 伪类定义的最后一个字符串是错误的。应该是
woof
定义为Dog
原型的属性。_super
只能作为Dog
构造函数的属性使用。The last string of the Dog pseudo-class definition is wrong. It should be
woof
as the property of theDog
's prototype._super
is available only as the property of theDog
constructor.所以你的 woof 方法实际上是一个静态方法(如果你来自 java。基本上,它挂在 Dog 函数上,并且可以在没有 Dog 实例的情况下访问。即:Dog.woof())
让它工作对于狗的实例,您需要确保它是原型定义(同样,用 Java 类比,实际上是实例方法定义)。正如 qwertymik 所说,
那么你就可以做到
So your woof method is actually effectively a static method (If you're coming from java. Basically, it's hanging off the Dog function, and can be accessed without an instance of Dog. ie: Dog.woof())
To get it working with an instance of a dog, you want to make sure it's a prototype definition (again, with a Java analogy, effectively a instance method definition). As qwertymik said,
Then you'll be able to do
也许你的意思是这样做:
Maybe you mean to do this: