eddie0329 2020. 10. 26. 12:54
๋ฐ˜์‘ํ˜•

๐Ÿ“Œ ๋ชฉ์ฐจ

  • Introduction
  • What is proxy?
  • Basic Example of Proxy
  • Conclusion
  • Reference

๐Ÿ“Œ Introduction

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ์— Vue3 ๊ณต๋ถ€์™€ ๋‚˜๋งŒ์˜ ํ”„๋ ˆ์ž„์›Œํฌ ๋งŒ๋“ค๊ธฐ์—์„œ ๋‚˜์˜จ Proxy๋ผ๋Š” ๊ฐœ๋…์ด ์ƒ์†Œํ•˜์—ฌ ๊ฐœ๋…์„ ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.

๐Ÿ“Œ What is proxy?

Proxy๊ฐ์ฒด๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ์˜ ๊ธฐ๋ณธ ์ž‘์—…์— ๋Œ€ํ•œ ํ–‰์œ„์— ๋Œ€ํ•ด ์‚ฌ์šฉ์ž ์ปค์Šคํ…€ ๋™์ž‘์„ ์ •์˜ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

๊ธฐ๋ณธ์ ์ธ Proxy ์‚ฌ์šฉ:

new Proxy(target, handler);

target์€ Proxy๋กœ ๋žฉํ•‘ํ•  ๋Œ€์ƒ ๊ฐ์ฒด๋ฅผ ์ง€์ •ํ•ด์ฃผ๊ณ  handler๋Š” Proxy์˜ ๋™์ž‘์„ ์ •์˜ํ•˜๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

๐Ÿ“Œ Basic Example of Proxy

๋งŒ์•ฝ ํ•ธ๋“ค๋Ÿฌ๋ฅผ ์ง€์ •์„ ํ•ด์ฃผ์ง€ ์•Š๋Š”๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?

const target = {
  message1: "hello",
  message2: "hi",
};

const handler1 = {};

const proxy1 = new Proxy(target, handler1);
console.log(proxy1.message1); // hello
console.log(proxy1.message2); // hi

๊ทธ๋ ‡๋‹ค๋ฉด ์ผ๋ฐ˜์ ์ธ ๊ฐ์ฒด์™€ ๋™์ผํ•˜๊ฒŒ ๋™์ž‘์„ ํ•ฉ๋‹ˆ๋‹ค. handler์—๋Š” get, set, has, defineProperty, deleteProperty, construct, apply ๋“ฑ ์ด 13๊ฐ€์ง€ ํ•จ์ˆ˜๋ฅผ ํ•ธ๋“ค๋ง ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿผ ๊ฐ€์žฅ ๊ธฐ๋ณธ์ ์ธ get์„ ์‚ฌ์šฉํ•˜์—ฌ Proxy๋ฅผ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

const target = {
  message1: "hello",
  message2: "hi",
};

const handler = {
  get: function (target, prop, receiver) {
    console.log("target", target);
    console.log("prop", prop);
    console.log("receiver", receiver);
    return 10;
  },
};

const proxy = new Proxy(target, handler);
console.log(proxy.message1);
// target { message1: 'hello', message2: 'hi' }
// prop message1
// receiver { message1: 'hello', message2: 'hi' }
// 10
console.log(proxy.message2);
// target { message1: 'hello', message2: 'hi' }
// prop message2
// receiver { message1: 'hello', message2: 'hi' }
// 10

๐Ÿ“Œ Conclusion

์ด๋ ‡๊ฒŒ Proxy๊ฐ์ฒด์— ๋Œ€ํ•ด ๋งŒ๋“ค์–ด๋ณด์•˜์Šต๋‹ˆ๋‹ค. proxy์˜ ์‚ฌ์šฉ๋ฒ•์„ ์ œ๋Œ€๋กœ ๋ชจ๋ฅด๊ณ  ์žˆ์—ˆ๋Š”๋ฐ ์ด๋ฒˆ ๊ธฐํšŒ์— ์ •๋ฆฌ๋ฅผ ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค.

๐Ÿ“Œ Reference

๋ฐ˜์‘ํ˜•