0

次のコードの例として、すべてのインスタンスを手動で反復する必要なく、ローカライズされた値参照を使用して JavaScript 擬似クラスのすべてのインスタンスに追加されるプロパティ値を初期化する方法を見つけようとしています。

function A() {
    this.a = '0';
}

var a = new A();
var b = new A();

document.write(a.a + a.b + a.c + '<BR />');

A.prototype.b = '1';
Object.defineProperty(A.prototype, 'c', {
    writable: true,
    value: (function() { return(this.a + '|'); })()
});

document.write(a.a + a.b + a.c + '<BR />');

b.c = '3';

document.write(a.a + a.b + a.c + '<BR />');
document.write(b.a + b.b + b.c + '<BR />');

出力:

0undefinedundefined
01undefined|
01undefined|
013

しかし、望ましい条件下では次のように出力されます。

0undefinedundefined
010|
010|
013

編集:

明確にするために、値は「this」を介してアクセスされるオブジェクトのプロパティに初期化する必要があります。プロパティがオブジェクトに追加されるとき。get または set 呼び出しで遅延した方法ではなく、追加のローカル プロパティを使用しません。

4

2 に答える 2

1

アクセスできるようにする場合は、および記述子オプションthisを使用できません。とを使用する必要があります。この場合、割り当てた値をデフォルト値よりも優先させたいので、そのロジックを実行するのはあなた次第です。valuewritablegetset

Object.defineProperty(A.prototype, 'c', {
    get: function(){
      // If an overridden values was provided, then return that instead.
      if ('_c' in this) return this._c;
      return (this.a + '|');
    },
    set: function(val){
      this._c = val;
    }
});
于 2013-02-24T19:06:28.587 に答える
1

aプロパティから値を動的に計算するゲッター関数が必要なようです。

Object.defineProperty(A.prototype, 'c', {
    get: function() {
        return(this.a + '|');
    },
    set: function(x) { // overwritable:
        // create normal property directly on the object (not on the prototype)
        Object.defineProperty(this, 'c', {
            value: x,
            writable: true
        });
    }
});

現在のコードは次のように機能します

A.prototype.c = (function() { return(this.a + '|'); })(); // IEFE

wherethisはグローバル オブジェクトでありa、もちろん未定義です。

于 2013-02-24T20:17:36.050 に答える