javascript - Object.defineProperty() default value with getter/setter -


i messing around "classical" inheritance , i'm running issue. using object.defineproperty() add properties livingthing "class". want have default value, along property getter/setter.

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

i running following error:

uncaught typeerror: invalid property.  property cannot both have accessors , writable or have value, #<object> 

why getting error , best approach have default value , getter/setter property, using object.defineproperty()?

use function scoped variable defined property , set variable's initial value 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 have setter. that's what's causing error. can either have value/writable (data descriptor) or get/set (accessor descriptor).

as result, when call var l = new livingthing, l.isalive == true , after call l.kill(), l.isalive == false


Comments