javascript - 如何正确地将其绑定到 Javascript 中的 getter/setter
问题描述
假设我有一个类,它将其实例的属性存储在嵌套对象中:
this.Properties = {
"Position":{
"X": 400,
"Y": 100
},
"Colour": "#007fff7f"
};
我想为每个(嵌套)属性定义特殊的 getter/setter,以便我可以添加范围检查/自动更新特定于实例的 HTML 元素的属性等。当我用普通方法尝试时,我意识到我无法将范围绑定到 getter/setter 中的参数:
//(based on https://stackoverflow.com/a/16400626)
//Define function prototype for binding an argument without overriding the old this:
Function.prototype.BindArgs = function(...boundArgs){
const targetFunction = this;
return function (...args) { return targetFunction.call(this, ...boundArgs, ...args); };
};
//...
{
get X(){
return this.__X__;
},
set X(Scope, Value){
this.__X__ = Value;
Scope.HTMLElement.style.left = Value + "px";
}.BindArgs(this) //This is incorrect syntax
}
上面的代码没有运行:不是因为 BindArgs 是一个无效的原型,而是因为setter 实际上不是一个函数,所以它不起作用。答案建议使用实际上有效的 Object.defineProperty:
Object.defineProperty(this.Properties.Position, "X", {
"get": function(){
return this.__X__;
}
"set": function(Scope, Value){
this.__X__ = Value;
Scope.HTMLElement.style.left = Value + "px";
}.BindArgs(this)
});
现在,当我拥有上面示例中的一些属性时,这会很好,但是必须为数十个属性执行此操作变得非常乏味——尤其是对于嵌套属性。是否有另一种更整洁的方式来定义自定义 getter/setter 并能够将参数绑定到它们?正常的语法是理想的,因为它都在对象定义中,而不是像 Object.defineProperty 那样分散在各处。显而易见的答案是使用普通函数来获取/设置值,但这样做意味着必须重构大量代码......
解决方案
我建议您使用代理进行验证。它只需要极少的代码更改,您可以一口气处理多个属性。
let validator = {
set: function(obj, prop, value) {
//in any of these cases you can return false or throw an error to refuse the new value
switch(prop) {
case "X":
Scope.HTMLElement.style.left = value + "px";
break;
case "Y":
Scope.HTMLElement.style.top = value + "px";
break;
case "Colour":
Scope.HTMLElement.style.color = value;
}
obj[prop] = value;
return true;
}
};
this.Properties.Position = new Proxy(this.Properties.Position, validator);
this.Properties = new Proxy(this.Properties, validator);
请注意,这使用了一个快捷方式( 和 的相同验证器Properties
)Properties.Position
,如果您发现您可能有属性名称重叠,您可能需要多个validator
对象。
推荐阅读
- c - 出现错误:错误的文件描述符:***检测到堆栈粉碎***在写入客户端套接字时,但套接字描述符是正确的
- php - 将firebase时间戳转换为php日期
- c# - 算法正确性的证明
- python - 使用 Redis 在 C++ 和 python 之间共享 Opencv 图像
- sql - 使用 json 格式的 array_agg 检索一对多关系行 - postgresql
- android - 如何使用 espresso 执行按下多个按键事件
- python - Python:合并具有不同标题的csv数据
- android - 有没有办法在弹出窗口中创建 viewpager?
- angular - 具有来自父组件的属性的 Angular 子组件
- laravel - 如何在活泼的 PDF 中使用“Devnagri(马拉地语)字母”?