Yes you can, in this way it has the effect of a read only property.
In other words, it works only to have a 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: link )
But in this case the most correct would be to have a read-only property, and in this 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: link