9

私はこのJavaScriptを持っています:

var Type = function(name) {
    this.name = name;
};

var t = new Type();

今、私はこれを追加したい:

var wrap = function(cls) {
    // ... wrap constructor of Type ...
    this.extraField = 1;
};

だから私はできる:

wrap(Type);
var t = new Type();

assertEquals(1, t.extraField);

[編集]クラス (静的/共有) プロパティではなく、インスタンス プロパティが必要です。

ラッパー関数で実行されたコードは、実際のコンストラクターに貼り付けたかのように機能するはずです。

の型はType変更しないでください。

4

1 に答える 1

7

update:更新版はこちら

あなたが実際に探していたのは、 Type を別のクラスに拡張することでした。JavaScript でそれを行う方法はたくさんあります。私は実際には「クラス」を構築するnewおよびprototypeメソッドのファンではありません (私は寄生継承スタイルの方が好きです) が、ここに私が得たものがあります:

//your original class
var Type = function(name) {
    this.name = name;
};

//our extend function
var extend = function(cls) {

    //which returns a constructor
    function foo() {

        //that calls the parent constructor with itself as scope
        cls.apply(this, arguments)

        //the additional field
        this.extraField = 1;
    }

    //make the prototype an instance of the old class
    foo.prototype = Object.create(cls.prototype);

    return foo;
};

//so lets extend Type into newType
var newType = extend(Type);

//create an instance of newType and old Type
var t = new Type('bar');
var n = new newType('foo');


console.log(t);
console.log(t instanceof Type);
console.log(n);
console.log(n instanceof newType);
console.log(n instanceof Type);
于 2012-04-11T07:24:59.733 に答える