Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.defineProperty() default value with getter/setter

Tags:

javascript

I am messing around with some "classical" inheritance and I'm running into an issue. I am using Object.defineProperty() to add properties to my LivingThing "class". I want to have a default value, along with a property getter/setter.

http://jsfiddle.net/fmpeyton/329ntgcL/

I am running into the following error:

Uncaught TypeError: Invalid property.  A property cannot both have accessors and be writable or have a value, #<Object>

Why am I getting this error and what would be the best approach to have a default value and a getter/setter for a property, using Object.defineProperty()?

like image 860
Fillip Peyton Avatar asked Jan 08 '23 12:01

Fillip Peyton


1 Answers

Use a function scoped variable to back the defined property and set that variable's initial value to the default:

function LivingThing(){
    self = this;
    var isAlive = true;

    Object.defineProperty(self, 'isAlive', {
        get: function(){
            return isAlive;
        },
        set: function(newValue){
            isAlive = newValue;
        },
        configurable: true
    });

    self.kill = function(){
        self.isAlive = false;
    };
}

http://jsfiddle.net/329ntgcL/5/

writable isn't necessary because you have a setter. That's what's causing your error. You can either have value/writable (data descriptor) OR get/set (accessor descriptor).

As a result, when you call var l = new LivingThing, l.isAlive == true and after you call l.kill(), l.isAlive == false

like image 98
arcyqwerty Avatar answered Jan 14 '23 12:01

arcyqwerty