Reputation: 218
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);
Upvotes: 4
Views: 1149
Reputation: 281606
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.
Upvotes: 4
Reputation: 413682
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
Upvotes: 3