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
}
};
In php they have magic getters and setters, like this:
public function __set($key, $value) {
// assign value for key UserID to _userID property
}
public function __get($key) {
// return value of _userID for UserID property
}
And in vb.net they have properties with parameters:
Public Property Marks(Byval index as Integer) as Integer
Get
If (index < NoofSubjects()) And index >= 0 Then
return _marks(index)
Else
Throw new Exception("Index should be in the range 0 to " & (NoofSubjects-1))
End If
End Get
Set(Byval value as Integer)
If (index < NoofSubjects()) And index >= 0 Then
_marks(index) = value
Else
Throw new Exception("Index should be in the range 0 to " & (NoofSubjects-1))
End If
End Set
End Property