Object.defineProperty Setter 函数的多个参数

Multiple Parameters for Object.defineProperty Setter Function?

本文关键字:参数 函数 defineProperty Setter Object      更新时间:2023-09-26

是否可以为 Object.defineProperty setter 函数设置多个参数?

例如

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函数并传递给它两个参数。

是否可以为 Object.defineProperty setter 函数设置多个参数?

是的,但无法调用它们(Object.getOwnPropertyDescriptor(obj, "joe").set(null, false) 除外)。使用分配给属性的一个值obj.joe = "doe";) 调用资源库 - 不能一次分配多个值。

如果你真的需要它们(无论出于何种原因),最好使用基本的二传手方法(obj.setJoe(null, false))。

我对setter方法也有类似的困境,所以我以对象param结束:

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

我像这样使用它:

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

只是一个有趣的想法。

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);