자바스크립트 객체가 다른 객체로부터 메서트와 속성을 상속받는 메커니즘
let user = {
name: "Jone",
age: 45,
};
console.log(user);
console.log(user.name);//Jone
console.log(user.hasOwnProperty("email"));//false
위 객체에서는 hasOwnProperty가 정의되지 않았지만 사용 가능하다.
그 이유를 살펴보자
user 객체를 브라우저 개발자 도구로 들어가서 확인하면 객체 안에 prototype이라 정의된 객체가 있는 것을 볼 수 있다.
모든 객체는 global Object prototype을 가진다.
function Person(name, email, birthdays) {
// 생성자 함수
this.name = name;
this.email = email;
this.birthday = new Date(birthdays);
this.calculateAge = function () {
const now = new Date();
const diff = now - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
}
const John = new Person("John", "John@test.com", "7-10-91");
const Han = new Person("Han", "Han@test.com", "2-11-91");
console.log("John", John);//John John
console.log("Han", Han);//Han Han
console.log(John.calculateAge());//33
console.log(Han.calculateAge());//33
위 코드를 확인하면
이런 결과가 나온다. 이때 name과 email, birthday는 서로 값이 다르기에 재사용 할 수 없다.
하지만 calculate함수는 두 객체가 똑같기 때문에 재사용 할 수 있다.
prototype에 calculateAge함수를 넣어 재사용한다.
function Person(name, email, birthdays) {
//생성자 함수
this.name = name;
this.email = email;
this.birthday = new Date(birthdays);
}
Person.prototype.calculateAge = function () {
const now = new Date();
const diff = now - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
const John = new Person("john", "John@test.com", "7-10-91");
const Han = new Person("Han", "Han@test.com", "2-11-91");
console.log("John", John);
console.log("Han", Han);
관리자 도구로 확인하면 protoptype 안에 calculateAge함수가 들어간 걸 확인할 수 있다.
Object.create()
function Person(name, email, birthdays) {
//생성자 함수
let person = Object.create(personsPrototype);
person.name = name;
person.email = email;
person.birthday = new Date(birthdays);
return person;
}
const personsPrototype = {
calculateAge() {
const now = new Date();
const diff = now - this.birthday.getTime();
const ageDate = new Date(diff);
return Math.abs(ageDate.getUTCFullYear() - 1970);
},
};
const John = new Person("john", "John@test.com", "7-10-91");
const Han = new Person("Han", "Han@test.com", "2-11-91");
console.log("John", John);
console.log("Han", Han);
console.log(John.calculateAge());
console.log(Han.calculateAge());