객체의 변화나 접근을 중간에서 가로채서
get
이나set
으로 추가작업을 할 수 있다.
const myObj = {name : 'nsunny'};
const proxy = new Proxy (myObj, {
get : function(target, property, receiver) {
console.log('get value');
return target[property];
},
set : function(target, property, value) {
console.log('set value');
target[property] = value;
}
});
target
은 myObj
를 뜻함.
proxy.name = "kimnsunny";
name을 변경하면 자동으로 set
함수가 실행됨.
proxy.name;
name을 호출하면 자동으로 get
함수가 실행됨.
obj를 proxy안에 숨기거나 proxy를 통해 값이 변한 횟수를 셀 수 있다.
const proxy = new Proxy ({name : 'nsunny', changedValue : 0}, {
get : function(target, property, receiver) {
return (property in target) ? target[property] : "anonymous";
},
set : function(target, property, value) {
console.log('set value');
target['changedValue']++;
target[property] = value;
}
});
proxy.dkfjdafdaf;
target
이 갖고있지 않은 property
를 호출할 경우 "anonymous"
가 출력된다.
proxy.name = 'kimnsunny';
name
의 값을 변경할때마다 changedValue
값이 1씩 증가한다.
Anything new like this is always tough for me. Me and tech don’t really get along that well. Same goes for proxies. If you also don’t really get proxies but need them for work, click here. One of the most accessible articles for me. It’s not that hard once you start digging in. And if you find a trusted provider you can rely on, it’s even better.