Yes you can, that way makes the effect of a property read only.
I mean, it works to have only one getter:
var obj = {_valA: 0, _valB:0};
Object.defineProperty(obj, 'valA', { // exemplo A
get: function() {
return this._valA;
}
});
Object.defineProperty(obj, 'valB', { // exemplo B
get: function() {
return this._valB;
},
set: function(value) {
this._valB = value;
}
});
console.log(obj.valA); // 0
obj.valA = 10;
console.log(obj.valA); // 0 <- não mudou o valor
console.log('-------')
console.log(obj.valB); // 0
obj.valB = 10;
console.log(obj.valB); // 10 <- mudou o valor com o setter
(jsFiddle: https://jsfiddle.net/h3ju37ga/)
but in that case most correct would be to have a read-only property, read-only and in that case you should do so:
var obj = {};
Object.defineProperty(obj, 'val', {
enumerable: true,
writable: false,
value: 5
});
console.log(obj.val); // 5
obj.val = 10;
console.log(obj.val); // 5 <- não muda o valor
jsFiddle: https://jsfiddle.net/avgah0ko/
Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to proceed. You would help the community by identifying the best solution for you. You can accept only one of them, but you can vote for any question or answer you find useful on the entire site.
– Maniero