gpt4 book ai didi

javascript - 在javascript中继承函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:23:06 24 4
gpt4 key购买 nike

我有一个功能是彼此相似的。如何在不重复的情况下更轻松地声明函数

function constructor (name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}

function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// create a Penguin constructor here
function Penguin(name, numLegs){
this.name=name;
this.numLegs = numLegs;
}

// create a sayName method for Penguins here
Penguin.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// our test code
var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

最佳答案

你快到了。

// create a Penguin constructor here
function Penguin(name, numLegs){
Animal.call(this, name, numLegs);
};

// Reuse the prototype chain
Penguin.prototype = Object.create(Animal.prototype);
Penguin.prototype.constructor = Penguin;

关于javascript - 在javascript中继承函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668902/

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