将属性添加到JS对象

时间:2015-10-01 13:24:17

标签: javascript 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: ""}

1 个答案:

答案 0 :(得分:3)

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

如果要使用Object.createyou can pass in further properties in the second parameter创建与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版本更清晰且不易出错(特别是如果您想在不同时间添加多个属性)。

相关问题