1

例如:

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.");
}

但我想继续使用第一个示例中的样式,并尽可能将我的所有类方法定义在一个“.prototype”块中。

4

1 回答 1

1

看看 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;
}

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

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/

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

于 2013-08-11T05:14:56.937 回答