1

現在、次の構文を使用して、ゲッターとセッターでクラスを定義しています。

SomeObject = function() {

  this._propertyOne = 'test';

}

SomeObject.prototype.__defineGetter__('propertyOne', function() {

  return this._propertyOne;

});

SomeObject.prototype.__defineSetter__('propertyOne', function(value) {

  this._propertyOne = value;

});

次に、次のようにプロパティにアクセスできます。

var o = new SomeObject();
o.propertyOne = 'test2';
console.log(o.propertyOne);

非推奨でない defineProperty コマンドまたは類似のものを使用して同じことを達成するにはどうすればよいですか?

私はこのようなことを試しました:

Object.defineProperty(SomeObject.prototype, 'propertyOne', {
  get: function() {

    return this._propertyOne;

  }.bind(this),
  set: function(value) {

    this._propertyOne = value;

  }.bind(this)
});

しかし、うまくいきません。

4

1 に答える 1

5

を実行した時点Object.definePropertyでは、this値はあなたが望むものではありませんが、window(またはそのスニペットを実行するオブジェクト)です。これが実際に起こることです:

Object.defineProperty(SomeObject.prototype, 'propertyOne', {
  get: function() {

    return this._propertyOne;

  }.bind(window),
  set: function(value) {

    this._propertyOne = value;

  }.bind(window)
});

部品を取り外す.bind(this)と、正常に動作するはずです。

于 2012-06-01T14:14:52.020 に答える