Philipp Gfeller
Philipp Gfeller

Reputation: 1259

Add property to JS object

I know this may be a duplicate, but I have found a lot of questions that were similar to mine, but their answer did not answer mine. For example this page https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty did not contain the answer to my question, as far as I know.

This is what I have:

var User = function() {
  this.name = '';
}

User.prototype.password = '';
// or
Object.defineProperty(User.prototype, 'password', {enumerable: true, configurable: true, writable: true});

console.log(new User()); // User {name: ""}

This of course adds password to the prototype of the object, but I'd like to add the password as a member after the constructor has been defined. Is there a way to achieve this?

var User = function() {
  this.name = '';
}

User.prototype.password = '';

console.log(new User()); // User {name: "", password: ""}

Upvotes: 7

Views: 3764

Answers (1)

nils
nils

Reputation: 27174

If you want to create a new Object with the new operator, it might prove to be difficult, if you can't modify the constructor anymore. As far as I know, the the constructor is the only place where can defined instance variables if you are using the new operator.

If you were to create objects with Object.create, you can pass in further properties in the second parameter, which is similar to Object.defineProperty:

var User = function() {
  this.name = '';
}

User.prototype.xyz = ''; // Add whatever you need to your prototype

var o = Object.create(User.prototype, {
    'password': {enumerable: true, configurable: true, writable: true, value: ''}
});
User.call(o);

If you need to do this before Object creation, you could always wrap your original constructor in another function:

var User = function() {
  this.name = '';
}

User.prototype.xyz = ''; // Add whatever you need to your prototype

var originalUser = User;

var User = function() {
    this.password = '';
    originalUser.call(this);
}

User.prototype = originalUser.prototype;

var o = new User();

I personally find the Object.create version clearer and less error-prone (especially if you have multiple properties you want to add at different times).

Upvotes: 4

Related Questions