Seerramatutu
Seerramatutu

Reputation: 21

Is it possible to declare non enumerable property on javascript constructor?

I need to know if is possible to make instances of a javascript class that has non-enumerable attributes, for example

// Constructor
function MyClass(a) {
    Object.defineProperty(this, '_number', {
        enumerable: false
    });
    this.number = a; // Call setter for '_number'
}

// Getters and setters for '_number'
Object.defineProperty(MyClass.prototype, 'number', {
   get: function() {
       return this._number;
   },
   set: function(n) {
       // Validate 'n' here
       this._number = n;
   }
});

What I wanted this code to do is to define the property _number on any instance of MyClass, making it not enumerable so that instance private variables such as _number wouldn't be listed in, suppose, a for in structure. You would use the number getter/setter to alter the private variable _number.

I have tried declaring the _number and number properties both inside the constructor and on MyClass.prototype with no success...

Any help would be appreciated!

Upvotes: 1

Views: 1863

Answers (1)

Bergi
Bergi

Reputation: 665286

Your approach is fine, you just need to watch out for the other attribute values which default to false:

function MyClass(a) {
    Object.defineProperty(this, '_number', {
        value: 0,          // better than `undefined`
        writable: true,    // important!
        enumerable: false, // could be omitted
        configurable: true // nice to have
    });
    this.number = a; // Call setter for '_number'
}

// Getters and setters for '_number'
Object.defineProperty(MyClass.prototype, 'number', {
   get: function() {
       return this._number;
   },
   set: function(n) {
       // Validate 'n' here
       this._number = n;
   },
   enumerable: true,  // to get `.number` enumerated in the loop
   configurable: true // nice to have
});

Upvotes: 4

Related Questions