[javascript] proxy

sunny·2021년 1월 18일
0

🐣 javascript ES6

목록 보기
14/15
post-thumbnail

proxy

객체의 변화나 접근을 중간에서 가로채서 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;
  }
});

targetmyObj를 뜻함.

proxy.name = "kimnsunny";

name을 변경하면 자동으로 set함수가 실행됨.

proxy.name;

name을 호출하면 자동으로 get함수가 실행됨.


proxy 활용

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씩 증가한다.

profile
blog 👉🏻 https://kimnamsun.github.io/

1개의 댓글

comment-user-thumbnail
2025년 7월 10일

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.

답글 달기