我如何定义对象的属性,因此,如果其中一个更改,则所有其他属性都会自动更新。
到目前为止,我已经提出了以下代码,但是它不起作用:
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 :
get
一个用作该属性的吸气剂的函数,如果没有吸气剂,则为undefined。函数返回值将用作属性的值。默认为未定义。set
用作属性设置器的函数,如果没有设置器,则为undefined。该函数将仅将分配给属性的新值作为参数。默认为未定义。
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(/^[a-z]+ [a-z]+$/))
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句