ES6 proxy

  • Proxy๋กœ interception ๊ธฐ๋Šฅ ๊ตฌํ˜„

    • ์–ด๋–ค object๋ฅผ ๊ฐ€๋กœ์ฑ„์„œ ์ถ”๊ฐ€๋กœ ๋‹ค๋ฅธ ์ž‘์—…์„ ๋”ํ•˜๋Š” ๋ฐฉ์‹

    • Proxy๋Š” ํŠน์ • ๊ฐ์ฒด๋ฅผ ๊ฐ์‹ธ ํ”„๋กœํผํ‹ฐ ์ฝ๊ธฐ, ์“ฐ๊ธฐ์™€ ๊ฐ™์€ ๊ฐ์ฒด์— ๊ฐ€ํ•ด์ง€๋Š” ์ž‘์—…์„ ์ค‘๊ฐ„์—์„œ ๊ฐ€๋กœ์ฑ„๋Š” ๊ฐ์ฒด๋กœ, ๊ฐ€๋กœ์ฑ„์ง„ ์ž‘์—…์€ Proxy ์ž์ฒด์—์„œ ์ฒ˜๋ฆฌ๋˜๊ธฐ๋„ ํ•˜๊ณ , ์›๋ž˜ ๊ฐ์ฒด๊ฐ€ ์ฒ˜๋ฆฌํ•˜๋„๋ก ๊ทธ๋Œ€๋กœ ์ „๋‹ฌ๋˜๊ธฐ๋„ ํ•จ

let proxy = new Proxy(target, handler)

target โ€“ ๊ฐ์‹ธ๊ฒŒ ๋  ๊ฐ์ฒด๋กœ, ํ•จ์ˆ˜๋ฅผ ํฌํ•จํ•œ ๋ชจ๋“  ๊ฐ์ฒด๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
handler โ€“ ๋™์ž‘์„ ๊ฐ€๋กœ์ฑ„๋Š” ๋ฉ”์„œ๋“œ์ธ 'ํŠธ๋žฉ(trap)'์ด ๋‹ด๊ธด ๊ฐ์ฒด๋กœ, ์—ฌ๊ธฐ์„œ ํ”„๋ฝ์‹œ๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค(์˜ˆ์‹œ: get ํŠธ๋žฉ์€ target์˜ ํ”„๋กœํผํ‹ฐ๋ฅผ ์ฝ์„ ๋•Œ, set ํŠธ๋žฉ์€ target์˜ ํ”„๋กœํผํ‹ฐ๋ฅผ ์“ธ ๋•Œ ํ™œ์„ฑํ™”๋จ).
proxy์— ์ž‘์—…์ด ๊ฐ€ํ•ด์ง€๊ณ , handler์— ์ž‘์—…๊ณผ ์ƒ์‘ํ•˜๋Š” ํŠธ๋žฉ์ด ์žˆ์œผ๋ฉด ํŠธ๋žฉ์ด ์‹คํ–‰๋˜์–ด ํ”„๋ฝ์‹œ๊ฐ€ ์ด ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•  ๊ธฐํšŒ๋ฅผ ์–ป๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ํŠธ๋žฉ์ด ์—†์œผ๋ฉด target์— ์ž‘์—…์ด ์ง์ ‘ ์ˆ˜ํ–‰๋ฉ๋‹ˆ๋‹ค.

const myObj = { name: 'mcm', changedValue: 0}

const proxy = new Proxy(myObj, {
	get: function(target, property, receiver) { // getํŠธ๋žฉ
		console.log('get value')
		return target[property]
	},
	set: function(target, property, value) { // setํŠธ๋žฉ
		console.log('set value')
		++target['changedValue'];
		target[property] = value
	}
})

proxy.name = 'hihi' // set value
console.log(proxy.name) // get value , hihi

Last updated