Object.defineProperty Setter 函数有多个参数?

问题描述 投票:0回答:3

Object.defineProperty setter 函数是否可以有多个参数?

EG

var Obj = function() {
  var obj = {};
  var _joe = 17;

  Object.defineProperty(obj, "joe", {
    get: function() { return _joe; },
    set: function(newJoe, y) {
      if (y) _joe = newJoe;
    }
  });

  return obj;
}

我没有从语法中得到任何错误,但我不知道如何调用 setter 函数并向其传递两个参数。

javascript setter defineproperty
3个回答
13
投票

Object.defineProperty setter 函数是否可以有多个参数?

是的,但无法调用它们(

Object.getOwnPropertyDescriptor(obj, "joe").set(null, false)
除外)。 setter 是通过分配给属性的一个值 (
obj.joe = "doe";
) 来调用的 - 你不能一次分配多个值。

如果你确实需要它们(无论出于何种原因),最好使用基本的 setter 方法 (

obj.setJoe(null, false)
)。


7
投票

我在 setter 方法上也遇到了类似的困境,所以我以对象结束

param
(ES5 及更早版本):

  set size(param) {
    this.width = param.width;
    this.height = param.height;
  }

从 ES6 开始,我们可以利用解构功能来简化 setter,如下所示:

  set size({width, height}) {
    this.width = width;
    this.height = height;
  }

我这样使用它:

this.size = {width: 800, height: 600};

-1
投票

只是一个有趣的想法。

var Joe = (function() {

    // constructor
    var JoeCtor = function() {

        if (!(this instanceof Joe)){
            throw new Error('Error: Use the `new` keyword when implementing a constructor function');
        }

        var _age = 17;

        // getter / setter for age
        Object.defineProperty(this, "age", {
            get: function() { return _age; },
            set: function(joeObj) {
                if (joeObj.assert) { 
                    _age = joeObj.value; 
                }
            }
        });

    };

    // static
    JoeCtor.ageUpdateRequest = function(canSet, newAge){
        return { assert: canSet, value: newAge }
    };

    return JoeCtor;

})();

myJoe = new Joe();

myJoe.age = Joe.ageUpdateRequest(true, 18);
© www.soinside.com 2019 - 2024. All rights reserved.