toddmo toddmo - 2 months ago 7
Javascript Question

How to emulate a property with arguments in JavaScript?

Edit This is not a duplicate b/c I can't use a setter b/c of its limitaions, and these are not "dynamic" properties that don't get defined until runtime. I was looking for the same thing that vb.net supports...property setters with arguments. In such a case you get the extra arguments coming into the setter of the property, but the property is defined at runtime (yes I guess it's a meta property). I knew that won't work so was looking for an emulation of that.

I can use any solution up through ES6 if that helps, but I don't have to. This isn't necesarily an ES6 question.

Is there any way in the language to emulate the calling convention I seek?

var myClass = new MyClass();
myClass.Setting('mysettingname') = 4;


I know I can do something like
myClass.Setting['mysettingname'] = 4;
, but I need code to run when it's set. That's the wrinkle.

ES5.1 JavaScript Setters are not a solution. If you add an argument to the setter it won't run:

MyClass = function(){

set setting(name, value) { // error b/c of name
// code that needs to run
}
};

Answer

You can use a Proxy:

class MyClass {}

const myClass = new Proxy(new MyClass, {set: (target, property, value) => {
  // Do here whatever you want with property and value
  console.log(`property: ${property}, value: ${value}`)
  return target[property] = value
}})

myClass.mysettingname = 4