2

class-extend.jsを使用して、JS コードに単純な継承を実装しています。

var Man = Class.extend({
    init: function(name) {
        this.name = name;
    }
});

var Mr = Man.extend({
    init: function(name) {
        this._super("Mr. " + name);
    }
});

var mrBean = new Mr("Bean");

JSFiddle

class-extend.js なしで実装されたオブジェクトから継承するには、スクリプトをどのように変更すればよいですか?

function AnotherMan(name) {
    this.name = name;
}

...
?
4

2 に答える 2

2

.call()関数で使用できますextendinitこれは、プロトタイプ メソッドがコンストラクターを指すことを想定しています。

function AnotherMan(name) {
    this.name = name;
}
AnotherMan.prototype.init = AnotherMan; // = AnotherMan.prototype.constructor;

var Mr = Class.extend.call(AnotherMan, {
    init: function(name) {
        this._super("Mr. " + name);
    }
});
var mrBean = new Mr("Bean");

(更新されたデモ)

もちろん、そのライブラリの代わりにネイティブの正しい JavaScript 継承Classを使用する方が簡単かもしれません…</p>

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    AnotherMan.call(this, "Mr. " + name);
}
Mr.prototype = Object.create(AnotherMan.prototype, {
    constructor: {value: AnotherMan}
});

var mrBean = new Mr("Bean");
于 2013-10-06T20:15:58.937 に答える
0

以下は、探しているものを実現します: ( working jsFiddle )。古典的な継承を実現するために、プロトタイプ チェーンを使用します。

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    AnotherMan.call(this, name); // Call the superclass's constructor in the scope of this.
    this.name = "Mr. " + name; // Add an attribute to Author.
}

Mr.prototype = new AnotherMan(); // Set up the prototype chain.
Mr.prototype.constructor = Mr; // Set the constructor attribute to Mr.

var mrBean = new Mr("Bean");

これを関数に一般化できます: (別の作業 jsFiddle )

function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;

    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

次のように使用します。

function AnotherMan(name) {
    this.name = name;
}

function Mr(name) {
    Mr.superclass.constructor.call(this, name);
    this.name = "Mr. " + name;
}
extend(Mr, AnotherMan);

var mrBean = new Mr("Bean");
于 2013-10-06T20:12:03.333 に答える