首页 > 解决方案 > 如何正确地将其绑定到 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 那样分散在各处。显而易见的答案是使用普通函数来获取/设置值,但这样做意味着必须重构大量代码......

标签: javascriptbindgetter-setterdefineproperty

解决方案


我建议您使用代理进行验证。它只需要极少的代码更改,您可以一口气处理多个属性。

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);

请注意,这使用了一个快捷方式( 和 的相同验证器PropertiesProperties.Position,如果您发现您可能有属性名称重叠,您可能需要多个validator对象。


推荐阅读