我知道这可能是一个重复的问题,但我发现很多类似于我的问题,但它们的答案并没有回答我的问题。例如,这个页面https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty,据我所知,也没有包含我的问题的答案。
请注意,Object.defineProperty()方法是用于在对象上定义新属性或修改现有属性的方法。如果您需要了解如何使用此方法,请参考MDN文档中的示例和详细说明。
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: ""}
defineProperty(User.prototype, ...
。无论如何,我不明白你试图通过将password
放在原型上来实现什么目的。难道它不需要像name
一样成为每个用户都不同的实例属性吗? - user663031User
函数添加更多的实例属性。这就是我在我的答案中试图解决的问题。 - nils