3

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!

Shutterfly
  • 199
  • 12

3 Answers3

3

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);
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • you can't have the property `writable` with `get` or `set` -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty `If a descriptor has both value or writable and get or set keys, an exception is thrown.` – Olivier Boissé May 04 '19 at 12:28
0

Assuming you're just trying to make a straightforward property, you just want it to be writable:

Object.defineProperty(this, 'name', {
  value: 'Caaaarl',
  writable: true
});

Then you can do this to change the value:

this.name = 'Carl';
Cruseydr
  • 46
  • 3
0

You do not need to rewrite the setter and getter if you are not customizing them.

This create the "name" property and sets as default Caarl

Object.defineProperty(this, 'name', {
   value: 'Caaarl'
});

If you need to customize the setter and getter, the variable scoping(as you are doing) is the official way.

By the way, you can also refer to the object with this:

var a = {};
Object.defineProperty(a, 'random', {
  get: function() { return 'Getter -> ' + this._random; },
  set: function(x) { this._random = 'Setter -> ' + x; }
});

So a default could be as simple as:

var a = {_random: 'default'};
console.log(a.random); //undefined
Object.defineProperty(a, 'random', {
  get: function() { return 'Getter -> ' + this._random; },
  set: function(x) { this._random = 'Setter -> ' + x; }
});
console.log(a.random);//undefined but getting custom getter
a.random = 'daniel';
console.log(a.random);//sweet
Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28