자바스크립트에서는 Object.create()라는 내장 메서드를 사용해 기존 객체를 프로토타입으로 삼는 새로운 객체를 만들 수 있습니다. 이 방식을 활용하면 기존 객체가 가진 속성들을 새로 생성된 객체에 그대로 상속할 수 있으며, 필요에 따라 상속받은 값을 덮어써 자신만의 속성을 정의할 수도 있습니다.
문법
Object.create(기존객체);
이 메서드는 인수로 전달된 기존 객체를 프로토타입으로 설정한 새로운 객체를 반환합니다. 즉, 기존 객체의 속성들이 프로토타입 체인을 통해 새 객체로 상속됩니다.
예제
다음 예제에서는 먼저 "person"이라는 객체를 생성합니다. 그다음 Object.create()를 사용해 이 객체를 프로토타입으로 하는 새로운 객체를 만들어 변수 "newper"에 할당합니다. 이후 newper 객체에서 상속받은 속성 값들을 변경하면, 원본 객체(person)의 값은 그대로 유지되면서 새 객체의 출력 결과만 달라지는 것을 확인할 수 있습니다.
<html>
<body>
<script>
var person = {
name: "Karthee",
profession: "Actor",
industry: "Tamil"
};
document.write(person.name);
document.write("</br>");
document.write(person.profession);
document.write("</br>");
document.write(person.industry);
document.write("</br>");
document.write("프로토타입을 사용해 기존 객체의 속성이 다음과 같이 변경되었습니다");
document.write("</br>");
var newper = Object.create(person); // 자체 프로토타입 생성
newper.name = "sachin";
newper.profession = "cricketer";
newper.industry = "sports";
document.write(newper.name);
document.write("</br>");
document.write(newper.profession);
document.write("</br>");
document.write(newper.industry);
</script>
</body>
</html>실행 결과
Karthee Actor Tamil 프로토타입을 사용해 기존 객체의 속성이 다음과 같이 변경되었습니다 sachin cricketer sports
동작 원리 정리
Object.create(person)으로 생성된 newper 객체는 person을 프로토타입으로 가지므로, name·profession·industry 같은 속성에 접근할 때 먼저 자기 자신의 속성을 찾고, 없으면 프로토타입인 person에서 값을 가져옵니다. 위 예제에서는 newper에 직접 새로운 값을 할당했기 때문에 상속받은 값 대신 새로 지정한 값이 출력됩니다. 반면 person 객체 자체는 수정되지 않으므로, 하나의 객체를 원형으로 삼아 여러 파생 객체를 효율적으로 만들 때 Object.create()가 유용하게 활용됩니다.