gpt4 book ai didi

javascript - 如何将 JavaScript 原型(prototype)对象扩展两次?

转载 作者:行者123 更新时间:2023-11-27 23:35:04 25 4
gpt4 key购买 nike

很难用语言表达我想要的内容,因此我编写了一个 JS 示例来帮助理解要点。

http://jsfiddle.net/w8Lfyxtr

  // create animal class
var animal = function(name) {
this.name = name;
};

animal.prototype.getSound = function() {
return this.sound === undefined ? 'nothing' : this.sound;
};


// create animal type classes
var dog = new animal("dog");
dog.prototype.sound = "woof";

var cat = new animal("cat");
dog.prototype.sound = "meow";

var worm = new animal("worm");


// create specific animals
var spot = new dog();
var mittens = new cat();
var squiggles = new worm();

我想创建 JavaScript 函数的实例并多次扩展原型(prototype),以便在我的示例中,特定动物具有其属和一般动物王国的方法和属性。

不幸的是,在第一次实例化之后,prototype属性就不再存在了。我不想继续扩展它,让主原型(prototype)拥有所有动物的所有方法,蠕虫和狗应该能够有 .dig(),猫应该能够有 .climb() 而其他类没有这些方法。

相反,我不想不断地将方法重新绑定(bind)到每个实例。 Mittens 猫应该具有与 cat 类相同的原型(prototype),并且应该具有与 Crookshanks 猫完全相同的函数对象,而无需完成任何额外的赋值工作。

如何通过我的示例实现这一目标?

最佳答案

而不是创建特定动物的实例,即:new Animal('dog');创建狗构造函数:

var Dog = function() {
this.sound = 'woof';
};
Dog.prototype = animal.prototype;
new Dog();

对象没有原型(prototype)属性,只有函数有。

您还可以使用Object.create:

Dog.prototype = Object.create(animal.prototype);

关于javascript - 如何将 JavaScript 原型(prototype)对象扩展两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197287/

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