Defining Javascript Getter And Setter Functions
Defining a function inside object:
let o = {
a() {
return 42;
}
};
console.log(o);
console.log(o.a);
console.log(o.a());
Output:
From above we can see a()
is an ordinary function.
Now rewriting a()
as a getter function:
// -----------------------
let o2 = {
get a() {
return 42;
}
};
console.log(o2);
console.log(o2.a);
// console.log(o2.a()); // Uncaught TypeError: o2.a is not a function
In above code the a()
is defined with get
so it’s a getter function. Here’s the output of the code:
Above is the getter function. To define a setter function, here is the example:
let o3 = {
v: 0,
set a(x) {
this.v = x;
}
};
console.log(o3);
o3.a = 42;
console.log(o3.v);
In above we define a function a()
and prefixed it with set
, and then we can set the value of v
by o3.a = 42
.
Here is the output of the code:
Finally here is the code showing how to add getter and setter functions by the Object.defineProperties()
function:
// ------------------------
let o4 = {
v: 0
};
Object.defineProperties(o4, {
'g': {
get: function () {
return this.v;
}
},
's': {
set: function (x) {
this.v = x;
}
}
});
console.log(o4.g);
o4.s = 42;
console.log(o4.g);
Here is the output of the above code: