[javascript] 프로퍼티 디스크립터를 활용한 객체 복제
자바스크립트에서 객체를 복제하는 방법은 여러 가지가 있습니다. 하지만 간단하면서도 유연한 방법 중 하나는 Object.getOwnPropertyDescriptor
메서드를 활용하는 것입니다. 이 메서드는 주어진 객체의 특정 프로퍼티에 대한 디스크립터를 반환합니다.
아래는 Object.getOwnPropertyDescriptor
메서드를 사용하여 객체를 복제하는 예제입니다.
const obj = {
name: "John",
age: 30,
address: {
city: "Seoul",
country: "South Korea"
}
};
// 원본 객체의 프로퍼티 디스크립터를 가져옵니다.
const descriptor = Object.getOwnPropertyDescriptor(obj, "name");
// 새로운 객체에 프로퍼티를 추가하고, 프로퍼티 디스크립터를 설정합니다.
const copiedObj = Object.create(Object.getPrototypeOf(obj), {
name: descriptor,
age: Object.getOwnPropertyDescriptor(obj, "age"),
address: Object.getOwnPropertyDescriptor(obj, "address")
});
console.log(copiedObj);
위 예제에서는 Object.getOwnPropertyDescriptor
메서드를 사용하여 원본 객체의 name
, age
, address
프로퍼티에 대한 디스크립터를 가져옵니다. 그리고 Object.create
메서드를 사용하여 copiedObj
를 생성하며, name
, age
, address
프로퍼티 디스크립터를 전달하여 객체를 복제합니다.
결과적으로 copiedObj
는 obj
를 복제한 새로운 객체가 됩니다.
이와 같은 방법을 사용하면 객체를 복제할 때 프로퍼티의 디스크립터를 유지할 수 있어서, 원본 객체와 복제된 객체 사이의 연결이 유지됩니다.
참고 자료: