LoginSignup
3
3

More than 5 years have passed since last update.

メモ:definePropertyとconfigurable

Posted at

既に設定されているプロパティをラップしたりしたかった。


var o = {};

Object.defineProperty(o, 'test', {
  get: function() {
    return 'a';
  }
});

console.log(o.test); // -> 'a';

Object.defineProperty(o, 'test', { // Error: Cannot redefine property: test
  get: function() {
     return 'b';
  }
});

デフォルトだと再定義でエラーが出る。
再定義(変更)可能にするにはconfigurableが必要らしい。


var o = {};

Object.defineProperty(o, 'test', {
  get: function() {
    return 'a';
  },
  configurable: true
});

console.log(o.test); // -> 'a';

Object.defineProperty(o, 'test', {
  get: function() {
     return 'b';
  }
});

console.log(o.test); // -> 'b';

ちなみに2回目以降は変更された箇所が反映されるらしい。


var o = {};

Object.defineProperty(o, 'test', {
  get: function() {
    return 'a';
  },
  configurable: true
});

console.log(o.test); // -> 'a';

Object.defineProperty(o, 'test', {
  get: function() {
     return 'b';
  }
});

console.log(o.test); // -> 'b';


Object.defineProperty(o, 'test', {
  get: function() {
     return 'c';
  },
  configurable: false
});

console.log(o.test); // -> 'c';



Object.defineProperty(o, 'test', { // Error: Cannot redefine property: test
  get: function() {
     return 'd';
  }
});

@google chrome 32.0.1700.102

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3