简体   繁体   中英

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: ""} 

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM