Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access value in getter inside defineProperty

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!

like image 751
Shutterfly Avatar asked Dec 06 '25 04:12

Shutterfly


1 Answers

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);
like image 198
Alnitak Avatar answered Dec 07 '25 17:12

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!