JavaScript

프록시(Proxy) 객체 JavaScript에서 사용 방법(옵저버 패턴)

cob 2023. 1. 9. 14:57
Proxy

 

 

프록시 객체란?
프록시(proxy) 객체는 어떠한 대상의 기본적인 동작(속성 접근, 할당, 순회, 열거, 함수 호출 등)의 작업을 가로챌 수 있는 객체를 뜻하며 자바스크립트에서 프록시 객체는 두 개의 매개변수를 가진다.

 

 

 


1. 사용 방법

const proxy = new Proxy(target, handler)
  • target : 프록시할 대상
  • handler : 프록시 객체의 traget 동작을 가로채서 정의할 동작들이 정해져 있는 함수

 

Handelr  작동 시점
get 프로퍼티를 읽을 때
set 프로터티에 값을 쓸 때
has in 연산자가 작동할 때
deleteProperty delete 연산자가 작동할 때
apply 함수를 호출할 때
constructor new 연산자가 작동할 때
getPrototypeOf Object.getPrototypeOf
setPrototypeOf Object.setPrototypeOf
isExtensible Object.isExtensible
preventExtensions Object.preventExtensions
getOwnPropertyDescriptor Object.getOwnPropertyDescriptor
ownKeys Object.getOwnPropertyNames
Object.getOwnPropertySymbols
  • 프록시 객체의 get() 함수는 속성과 함수에 대한 접근을 가로챈다.
  • 프록시 객체의 has() 함수는 in 연산자의 사용을 가로챈다.
  • 프록시 객체의 set() 함수는 속성에 대한 접근을 가로챈다.

 


2. 프록시 객체 구현 코드 (Get)

const handler = {
	get : function(target, name) {
		return name === 'name' ? `${target.a} ${target.b}` : target[name]
	}
}
const p = new Proxy({a: 'KUNDOL', b: 'IS AUMUMU ZANGIN'}, handler)
console.log(p.name) // KUDOL IS AUMUMU ZANGIN
  • p라는 변수에 name이라는 속성을 선언하지 않았는데도 p.name으로 name 속성에 접근하려고 할 때, 로채 문자열을 만들어 반환한다.

 

 


3. 프록시 객체를 이용한 옵저버 패턴 (Set)

function createReactiveObject(target, callback) {
	const proxy = new Proxy(target, {
		set(obj, prop, value) {
			if (value !== obj[prop]) {
				const prev = obj[prop]
				obj[prop] = value
				callback(`${prop}가 [${prev}] >> [${value}] 로 변경되었습니다. `)
			}
			return true
		}
	})
	return proxy
}

const a = { "형규" : "솔로" }
const b = createReactiveObject(a, console.log)
b.형규 = "솔로"
b.형규 = "커플"
// 형규가 [솔로] >> [커플] 로 변경되었습니다.
  • set() 함수를 통해 속성에 대한 접근을 가로채 형규라는 속성이 솔러에서 커플로 되는 것을 감시할 수 있다.

 

 

 

반응형