繁体   English   中英

将属性添加到JS对象

[英]Add property to JS object

我知道这可能是重复的,但我发现了许多类似于我的问题,但他们的回答没有回答我的问题。 例如,据我所知,此页面https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty不包含我的问题的答案。

这就是我所拥有的:

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

这当然会为对象的原型添加密码,但是我想在定义构造函数后将密码添加为成员。 有没有办法实现这个目标?

 var User = function() { this.name = ''; } User.prototype.password = ''; console.log(new User()); // User {name: "", password: ""} 

如果你想用new运算符创建一个新的Object,那么如果你不能再修改构造函数就可能会很困难。 据我所知,如果你使用new运算符,构造函数是唯一可以定义实例变量的地方。

如果要使用Object.create创建对象,则可以在第二个参数中传入更多属性,类似于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);

如果您需要在创建对象之前执行此操作,则始终可以将原始构造函数包装在另一个函数中:

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();

我个人觉得Object.create版本更清晰,更不容易出错(特别是如果你想在不同时间添加多个属性)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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