[英]Make all properties of object mutable
我如何定義對象的屬性,因此如果其中之一發生更改,所有其他屬性都會自動更新。
到目前為止,我已經提出了以下代碼,但是它不起作用:
function CreateNamed(first, last) {
Object.defineProperties(this, {
"firstName": {
value: first,
writable: true
},
"lastName": {
value: last,
writable: true
},
"fullName": {
value: first + ' ' + last,
writable: true
}
});
}
因此,在創建新對象之后,可以對其進行適當的更改:
var b = new CreateNamed('Bill', 'Gates'); // Bill Gates
b.firstName = 'Paul'; // b.fullName = Paul Gates
b.lastName = 'Wood'; // b.fullname = Paul Wood
b.fullName = 'Chuck Norris' // b.firstName = Chuck, b.lastName = Norris
value
不是動態計算的。 它不會隨着對象的改變而改變。 為了動態計算屬性,您需要使用get
和set
定義getter和setter:
得到
用作屬性的吸氣劑的函數,如果沒有吸氣劑,則未定義。 函數返回值將用作屬性的值。 默認為未定義。組
用作屬性設置器的函數,如果沒有設置器,則未定義。 該函數將僅將分配給屬性的新值作為參數。 默認為未定義。
function CreateNamed(first, last) { this.first = first; this.last = last; Object.defineProperties(this, { "firstName": { get: function() { return this.first; }, set: function(name) { this.first = name; } }, "lastName": { get: function() { return this.last; }, set: function(name) { this.last = name; } }, "fullName": { get: function () { return this.first + ' ' + this.last }, set: function (name) { if (!name.match(/^[az]+ [az]+$/)) throw new Error('I cannot parse that name') var parts = name.split(' ') this.first = parts[0]; this.last = parts[1]; } } }); } var user = new CreateNamed('bob', 'smith'); document.write(user.fullName); // bob smith user.firstName = "john"; document.write(user.fullName); // john smith user.fullName = "tony brian"; document.write(user.firstName); // tony document.write(user.lastName); // brian
@meagar的答案是正確的。
但是有一種更簡單的方法:像往常一樣分配firstName
和lastName
屬性,然后只為fullName
定義一個getter和setter:
function CreateNamed(first, last) {
this.firstName = first;
this.lastName = last;
Object.defineProperty(this, "fullName", {
get: function () { return this.firstName + ' ' + this.lastName },
set: function (name) {
name = name.split(' ');
if(name.length != 2) throw new Error('I cannot parse that name');
this.firstName = name[0];
this.lastName = name[1];
}
});
}
function CreateNamed(first, last) { this.firstName = first; this.lastName = last; Object.defineProperty(this, "fullName", { get: function () { return this.firstName + ' ' + this.lastName }, set: function (name) { name = name.split(' '); if(name.length != 2) throw new Error('I cannot parse that name'); this.firstName = name[0]; this.lastName = name[1]; } }); } var ouput = []; var user = new CreateNamed('bob', 'smith'); ouput.push(user.fullName); // bob smith user.firstName = "john"; ouput.push(user.fullName); // john smith user.fullName = "tony brian"; ouput.push(user.firstName); // tony ouput.push(user.lastName); // brian document.body.innerHTML = ouput.join('<br />');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.