Multiple Parameters for Object.defineProperty Setter Function?
Asked Answered
S

3

8

Is it possible to have multiple parameters for Object.defineProperty setter function?

E.G.

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

I don't get any errors from the syntax, but I can't figure out how to call the setter function and pass it two arguments.

Screed answered 10/9, 2013 at 19:22 Comment(1)
Why would you want that?Husch
H
13

Is it possible to have multiple parameters for Object.defineProperty setter function?

Yes, but it's not possible to invoke them (other than Object.getOwnPropertyDescriptor(obj, "joe").set(null, false)). A setter is invoked with the one value that is assigned to the property (obj.joe = "doe";) - you cannot assign multiple values at once.

If you really need them (for whatever reasons), better use a basic setter method (obj.setJoe(null, false)).

Husch answered 10/9, 2013 at 19:26 Comment(0)
P
13

I had a similar dilemma with setter method, so I ended with the object param (ES5 and earlier):

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

Since ES6 we can leverage destructuring feature simplifying the setter as follows:

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

And I use it like:

this.size = {width: 800, height: 600};
Plenitude answered 30/4, 2016 at 19:16 Comment(0)
R
-1

Just an interesting thought.

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);
Robbins answered 23/6, 2015 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.