Currently have this code defining getter/setter for an object’s selectedID property. The object is called Components.
_selectedID: null,
get SelectedID() {
return this._selectedID;
},
set SelectedID(val) {
if (!isNaN(val) && val != this._selectedID) {
this._notifyChanged(val);
this._selectedID = val;
}
},
While this works in the sense that the browser knows how to handle the javascript generated, Visual Studio states that there are syntax warnings.
This is another way to say the same thing, but lacks the OOPness of the previous:
(EDIT: Apparently I can use this instead of Components here, so ‘lacking OOPness’ isn’t as much of an issue, but still curious if better).
function GetSelectedID() {
//return Components._selectedID;
return this._selectedID;
}
function SetSelectedID(val) {
//if (!isNaN(val) && val != Components._selectedID) {
//Components._notifyChanged(val);
//Components._selectedID = val;
//}
if (!isNaN(val) && val != this._selectedID) {
this._notifyChanged(val);
this._selectedID = val;
}
}
Object.defineProperty(Components, 'SelectedID', { get: GetSelectedID
, set: SetSelectedID
, configurable: true
, enumerable: true });
Note that instead of saying this I need to say Components as this is setup outside of the Component’s object constructor. If I try to move the functions into the constructor I get syntax errors.
Does anyone know if it is possible to achieve both? Something like:
SelectedID: function () {
alert("Getter");
return this._selectedID;
},
SelectedID: function (val) {
alert("setter");
if (!isNaN(val) && val != this._selectedID) {
this._notifyChanged(val);
this._selectedID = val;
}
},
The above code does not work, though. When I say Components.SelectedID the getter alert does not fire.
There is no method overloading in Javascript so you are just redefining
SelectedIDwith the setter.If you want to have one method for both, try something like this:
I’m not arguing this is a good idea, it is just the way you would achieve what you are trying to do.