[英]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.