Is there a way in JavaScript's constructor functions to use getter and setter syntax for properties?
Here is an example of my desired syntax:
function DemoClass()
{
var mFooProperty = 0;
get FooProperty()
{
return mFooProperty;
}
set FooProperty(value)
{
mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
You can make use of a class in Javascript and set the properties as a class instance and then use getters/setters like
class DemoClass {
constructor() {
this.mFooProperty = 0;
}
get FooProperty() {
return this.mFooProperty;
}
set FooProperty(value) {
this.mFooProperty = value;
}
}
var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);
According to documentation:
The bodies of class declarations and class expressions are executed in
strict mode
i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.
In order to keep the real storage for that property as a private variable, you'd have to use an Object API to define the getter and setter in the constructor:
function DemoClass() {
var mFooProperty = 0;
Object.defineProperties(this, {
fooProperty: {
get: function() { return mFooProperty; },
set: function(value) { mFooProperty = value; }
}
});
}
Now when you construct an instance, the instance will appear to have a property called "fooProperty". Referencing the value of the property will invoke the "getter" function, and setting the value calls the "setter":
var d = new DemoClass();
console.log(d.fooProperty); // calls getter 0
d.fooProperty = 3; // calls setter
console.log(d.fooProperty); // 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With