什么是标准方式"将getter和setter添加到Object.prototype?

时间:2015-11-11 15:07:07

标签: javascript

我需要在对象的原型上创建gettersetter属性(ES5)。目前我正在使用以下代码,它可以工作,但我想知道:

  • 这是一种标准的方式"这样做?
  • 可以改为使用Object.defineProperties()吗?
  • 有更好的选择/ approches吗?

我的目标是ES5,仅限vanilla JS,浏览器环境。

实施例: https://jsfiddle.net/0yLotg35/

function Color() {}
Color.prototype = {
    _name: '',
    get name() {
        return this._name;
    },
    set name(value) {
        this._name = value;
    },
    _readOnly: true,
    get readOnly() {
        return this._readOnly;
    }
};

var myColor = new Color();
myColor.name = 'red';
alert(myColor.name);

alert(myColor.readOnly);
myColor.readOnly = false;
alert(myColor.readOnly); // value it is not changed

1 个答案:

答案 0 :(得分:1)

  1. 这是对象文字的标准方式。http://www.2ality.com/2015/08/object-literals-es5.html
  2. 是的,如果您需要动态添加属性,可以使用defineProperty

  3. 为什么需要替代方案?在不知道用例的情况下很难提出建议

  4. defineProperties

    var obj = {};
    Object.defineProperties(obj, {
      "property1": {
        value: true,
        writable: true
      },
      "property2": {
        value: "Hello",
        writable: false
      }
    });
    

    defineProperty

    function Archiver() {
      var temperature = null;
      var archive = [];
    
      Object.defineProperty(this, 'temperature', {
        get: function() {
          console.log('get!');
          return temperature;
        },
        set: function(value) {
          temperature = value;
          archive.push({ val: temperature });
        }
      });
    
      this.getArchive = function() { return archive; };
    }
    
    var arc = new Archiver();
    arc.temperature; // 'get!'
    arc.temperature = 11;
    arc.temperature = 13;
    arc.getArchive(); // [{ val: 11 }, { val: 13 }]
    

    原型上的getter和setter

    
    
    function Archiver() {
      // Can't define the array on the prototype or it would be shared by instances
      this._archive = [];
    }
    
    Archiver.prototype =  {
      _temperature: null,
      getArchive: function() { 
        return this._archive;
      }
    }
    
    Object.defineProperty(Archiver.prototype, 'temperature', {
      get: function() {
        return this._temperature;
      },
      set: function(value) {
        this._temperature = value;
        this._archive.push({ val: value });
      }
    });
    
    var arc = new Archiver();
    arc.temperature; // 'get!'
    arc.temperature = 11;
    arc.temperature = 13;
    console.log(arc.getArchive()); // [{ val: 11 }, { val: 13 }]
    
    var arc2 = new Archiver();
    arc2.temperature; // 'get!'
    arc2.temperature = 10;
    arc2.temperature = 15;
    console.log(arc2.getArchive()); // [{ val: 10 }, { val: 15 }]