gpt4 book ai didi

Javascript 原型(prototype)继承怪异

转载 作者:搜寻专家 更新时间:2023-11-01 04:55:24 25 4
gpt4 key购买 nike

我正在尝试处理一些 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'

我知道我可以将未找到的方法放入构造函数中,但我试图通过修改原型(prototype)来做到这一点。我在这里做错了什么?

最佳答案

改变:

Dog._super = Animal.prototype;
Dog.woof = function(){ console.log( "Woof!" ); _super.speak(); }

收件人:

// Dog.prototype._super = Animal.prototype; <- you can remove this line
Dog.prototype.woof = function(){ console.log( "Woof!" ); this.speak(); }

关于Javascript 原型(prototype)继承怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com