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

しかし、最初の例のスタイルを引き続き使用し、可能であればすべてのクラス メソッドを 1 つの ".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関数 forも機能するように定義する必要があります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 に答える