gpt4 book ai didi

Javascript - 可以模拟经典的 OOP 继承吗?

转载 作者:行者123 更新时间:2023-11-30 12:05:22 25 4
gpt4 key购买 nike

我想知道,考虑到 javascript 原型(prototype)继承的局限性,是否有可能模拟其他 OOP 语言中看到的基于类的继承。

我创建了一个父类(super class)和子类,如下所示:

//Parent
function Animal(i)
{
//Some constructor implementation
}

//Child
function Pig(i)
{
//Some additional constructor implementation
}

Pig.prototype = new Animal();

我能否确保子对象继承其父对象的功能,而无需显式调用它们或在子对象中创建它们?

Animal.prototype.eat = function()
{
console.log("eating...");
}

Pig.eat(); //No implementation of eat in the Pig object

我能否确保子级继承其父级的所有对象变量,而不是像这样显式调用父级的构造函数:

function Pig(i) 
{
User.call(this, i);
//Some pig-like variables
}

基本上,我想在我的父类中创建所有实现,并且只编写需要覆盖的函数以及子类中的任何附加函数。如果我想调用 Pig.eat(),如果子对象中不存在父函数,我希望它使用父函数。在创建一个 Pig 对象时,我希望它除了继承自己独特的变量外,还继承其父变量。这可能吗?

最佳答案

I'd like to create all the implementation in my parent class and only write functions that need to be overridden + any additional functions in the child class.

它实际上是这样工作的。可能你只是做错了什么,看这个例子:

//Parent
function Animal()
{
this.animalInstinct = true;
}

Animal.prototype.eat = function()
{
alert("eating...");
}

//Child
function Pig()
{
this.nose = 'pigNose'
}

Pig.prototype = new Animal();

pig = new Pig();

pig.eat(); //There is implementation of eat in the Pig object

另请注意,Pig.prototype = new Animal(); 在某些情况下可能会出现问题。例如,为了定义 Pig 类,您需要实例化 Animal 对象。对于需要将一些参数传递给构造函数的更复杂的对象,这可能不方便。

Recommended way就是做 Pig.prototype = Object.create(Animal.prototype)

关于Javascript - 可以模拟经典的 OOP 继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383899/

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