JavaScript 类 Getter/Setter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49895080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:49:14  来源:igfitidea点击:

JavaScript Class Getter/Setter

javascriptecmascript-6

提问by therabbityouknow

is there a way to listen for a property call on a JavaScript Class

有没有办法侦听 JavaScript 类上的属性调用

for example when i go something like this:

例如,当我做这样的事情时:

myForm =  new Form();

myForm.name = 'Name'; 

-> when i set the name i dont only want to set the property but i also want to update my Vuex store. Same thing with geti would like to read from Vuex store.

-> 当我设置名称时,我不仅想设置属性,而且还想更新我的 Vuex 商店。与get我想从 Vuex 商店读取相同的内容。

I knoew there are thins like Proxy but for this i need to wrap my Class with a Proxy object. Not so sure if i like this.

我知道有像 Proxy 这样的薄层,但为此我需要用一个 Proxy 对象包装我的类。不太确定我是否喜欢这个。

module.exports = new Proxy(new Form({}), {
    get (receiver, name) {
        console.log('getting property from Vuex Store');
    }
});

What i need is something like this:

我需要的是这样的:

module.exports = class Form {

//this should be triggered when form.something
get(property) {
return this[property];
}

//this should be triggered when from.something = 'something'
set(property, value) { 
return this[property] = value;
}
};

it there a best practice for this?

对此有最佳实践吗?

回答by Jamiec

Javascript supports gettersand setters

Javascript 支持gettersetter

class Form{
  set foo(val){
    console.log("setting foo")
    this.fooValue = val;
  }
  
  get foo(){
     console.log("getting foo");
     return this.fooValue;
  }
}

let frm = new Form();
frm.foo = "bar";
console.log(frm.foo);

You could make this more dynamic by writing a withGetterSettermethod which wraps each property of an object with a getter/setter.

您可以通过编写一个withGetterSetter方法来使这更加动态,该方法使用 getter/setter 包装对象的每个属性。

var form = {
  a: "aValue",
  b: "bValue"
}

function withGetterSetter(obj){
   var keys = Object.keys(obj);
   var result = {};
   
   for(var i=0;i<keys.length;i++){
       var key = keys[i];
       result[key+"_internal"] = obj[key];
       (function(k){
         Object.defineProperty(result,k, {
          get:function() {
            console.log("getting property:",k);
            return this[k + "_internal"];
          }, 
          set: function(x) { 
            console.log("setting property:",k);
            this[k + "_internal"] = x 
          }
         });
       })(key)
   }
   return result;
}

var setterObj = withGetterSetter(form);
console.log(setterObj.a);
setterObj.a = "updated";
console.log(setterObj.a);

It works by copying each property pto a new object with p_internaland creating a dynamic get/set for the original property name.

它的工作原理是将每个属性复制p到一个新对象,p_internal并为原始属性名称创建动态获取/设置。