can i access the value that i have defined inside a defineProperty call? I want create something like this:
Object.defineProperty(this, 'name', {
value: 'Caaaarl',
get: function() { return <the value>; },
set: function(x) { <the value> = x; }
});
Currently I have to create a second attribute for each property.
var _name = '';
Object.defineProperty(this, 'name', {
get: function() { return _name; },
set: function(x) { _name = x; }
});
Thanks for every help!
It's not legal to have both a value and either get or set fields in the property descriptor.
If you wish to make a more complicated property with getters and setters that do more than merely set the property without polluting the namespace, you may hold the underlying value in a closure:
(function() {
var value = 'Caaarl';
Object.defineProperty(this, 'name', {
get: function() {
// do some stuff
...
return value;
},
set: function(v) {
// do some stuff
...
value = v;
},
enumerable: true
});
}).call(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With