Add property to JS object

I know this may be a duplicate, but I found many questions that were similar to mine, but their answer did not answer me. For example, this page https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty did not contain an 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 the password to the prototype object, but I would like to add the password as a member after defining the constructor. Is there any way to achieve this?

 var User = function() { this.name = ''; } User.prototype.password = ''; console.log(new User()); // User {name: "", password: ""} 
+5
source share
1 answer

If you want to create a new object with the new operator, this can be tricky if you can no longer modify the constructor. As far as I know, the constructor is the only place where instance variables can be defined if you use the new operator.

If you were to create objects with Object.create , you can pass additional 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 creating the object, you can 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 believe that the version of Object.create is understandable and less error prone (especially if you have several properties that you want to add at different times).

+3
source

Source: https://habr.com/ru/post/1232718/


All Articles