所以我有一个名为 settings 的对象,它有一个名为 hex 的属性,它有自己的属性:
var settings = {
hex: {
hex: "4fdaef",
validate: function(){
if(this.hex.length == 6){
return true
}
}
}
}
因此,目前要获取十六进制值,我必须调用 settings.hex.hex,但理想情况下,我更希望能够仅调用 settings.hex 来获取十六进制值。我该如何实现这一目标?
最佳答案
您必须将 hex
重命名为 _hex
,但这会起作用:
var settings = {
get hex() {
return this._hex.hex;
},
_hex: {
hex: "4fdaef",
validate: function () {
if (this.hex.length == 6) {
return true
}
}
}
}
console.log(settings.hex); // 4fdaef
通过代理
,您可以允许settings.hex.validate()
调用_settings._hex._hex.validate()
,但它很快就变得非常难看,而且我们甚至还没有实现 settings.hex = 'some other color'
的预期行为所需的 setter
。
var _settings = {
_hex: {
_hex: new String('4fdaef'),
validate: function () {
if (this.length == 6) {
return true;
}
},
}
}
_settings._hex.hex = new Proxy(_settings._hex._hex, {
get(target, property) {
return property == 'validate' ? _settings._hex.validate : target[property];
}
});
const settings = new Proxy(_settings, {
get(target, property) {
return property == 'hex' ? target._hex.hex : target[property];
}
});
console.log(settings.hex); // [String: '4fdaef']
console.log(settings.hex.validate()); // true
关于javascript - 如何使得当调用对象而不调用其任何属性时,它返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63026119/