Can only use get without the set in Object.defineProperty?

Asked

Viewed 62 times

4

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

I understood that get calls a function when a property is read and that set calls a function when a value is saved to a property.

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

  • 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.

2 answers

3

1

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/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.