Is it possible to only use get without the set in Object.defineProperty?

3

I need to get more information about the get and set attributes of the Object.defineProperty() method.

I understand that get calls a function when a property is read and that set calls a function when a value is written to a property.

Can I use one without the other? For example, setting get without setting set ?

    
asked by anonymous 25.06.2016 / 02:21

2 answers

2

Yes, you can define only one of them according to your need. It is common to set both or set only get , but nothing prevents you from doing the opposite.

Object.defineProperty(obj, 'prop', {
  get: function() { return propValue; },
});

"Official" documentation .

    
25.06.2016 / 02:29
1

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

    
25.06.2016 / 09:51