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

Javascript - Possible to emulate classical OOP inheritance?

我想知道,考虑到 javascript 原型继承的局限性,是否可以模拟其他 OOP 语言中基于 class 的继承。

我创建了一个 superclass 和 subclass 如下:

//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
}

基本上,我想在父 class 中创建所有实现,并且只编写需要覆盖的函数 + 子 class 中的任何附加函数。如果我想调用 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 class,您需要实例化 Animal 对象。这对于需要将一些参数传递给构造函数的更复杂的对象来说可能不方便。

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

查看 ES6 方式,可以使用类似 Babel.

的方式轻松编译成 ES5
'use strict';
class Animal {
    constructor() {
    }

    eat() {
        console.log('Eating')
        return this;
    }

    play() {
        console.log('Do whatever an animal does...');
        return this;
    }
}

class Pig extends Animal {
    constructor() {
        super()
    }

    play() {
        // This overrides the Animal play method
        console.log('Roll in the mud!');
        return this;
    }

    makeBacon() {
        console.log('BACON!!');
    }
}

如果您想查看 ES5 版本,请将上面的内容复制粘贴到 Babel 的实时 testing console 中,或者在支持它的最新版本 Chrome 中测试它。 然后,您可以执行以下操作:

var pig = new Pig();
pig.eat().play().eat().makeBacon();