在JavaScript中,如何使用单个“”从子类中的父类继承;.原型;块

In JavaScript, how do I inherit from a parent class in child class using a single ".prototype" block?

本文关键字:子类 父类 继承 原型 JavaScript 何使用 单个      更新时间:2023-09-26

例如:

function Person() {
    //person properties
    this.name = "my name";
}
Person.prototype = {
    //person methods
    sayHello: function() {
        console.log("Hello, I am a person.");
    }
    sayGoodbye: function() {
        console.log("Goodbye");
    }
}
function Student() {
    //student specific properties
    this.studentId = 0;
}
Student.prototype = {
    //I need Student to inherit from Person
    //i.e. the equivalent of
    //Student.prototype = new Person();
    //Student.prototype.constructor = Person;
    //student specific methods
    //override sayHello
    sayHello: function() {
        console.log("Hello, I am a student.");
    }
}

我知道我可以使用实现这一点

function Student() {
    this.studentId = 0;
}
Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
    console.log("Hello, I am a student.");
}

但我想继续使用第一个例子中的样式,如果可能的话,将我所有的类方法定义在一个".protype"块中。

看看StackOverflow上的以下答案:https://stackoverflow.com/a/17893663/783743

这个答案引入了原型类同构的概念。简单地说,原型对象可以用来为类建模。以下代码取自上述答案:

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

使用上述方法,我们可以实现Person如下:

var Person = CLASS({
    constructor: function () {
        this.name = "my name";
    },
    sayHello: function () {
        console.log("Hello, I am a person.");
    },
    sayGoodbye: function () {
        console.log("Goodbye");
    }
});

然而,继承需要一些额外的工作。因此,让我们稍微修改一下CLASS函数:

function CLASS(prototype, base) {
    switch (typeof base) {
    case "function": base = base.prototype;
    case "object": prototype = Object.create(base, descriptorOf(prototype));
    }
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

我们还需要为CLASS的工作定义descriptorOf函数:

function descriptorOf(object) {
    return Object.keys(object).reduce(function (descriptor, key) {
        descriptor[key] = Object.getOwnPropertyDescriptor(object, key);
        return descriptor;
    }, {});
}

现在我们可以如下创建Student

var Student = CLASS({
    constructor: function () {
        this.studentId = 0;
    },
    sayHello: function () {
        console.log("Hello, I am a student.");
    }
}, Person);

亲自观看演示:http://jsfiddle.net/CaDu2/

如果您需要任何理解代码的帮助,请随时与我联系。