2021 프론트 엔드 로드맵 따라가기/JS
[중요] Prototypal inheritance
알 수 없는 사용자
2021. 6. 5. 17:07
JS에서 Constructor는 함수이다.
따라서 다음과 같은 코드실행이 가능하다.
// Person Constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Customer constructor
function Customer(firstName, lastName, phone, membership) {
Person.call(this, firstName, lastName);
this.phone = phone;
this.membership = membership;
}
// Create customer
const customer1 = new Customer("Tom", "Smith", "555-555-5555", "Standard");
console.log(customer1);
Person.call을 통해서 Person의 함수내용을 Customer 함수 안에서 실행할 수 있으며 첫번째 인자로 넘겨받은 this를 통해 Person의 this를 Customer의 this로 대체가능하다.
따라서 위의 코드는 customer1.firstName === Tom 의 결과를 갖게 된다.
하지만 이것은 Person의 함수 내용을 Customer에서 호출한 것이지 Person을 prototype으로 가지게 된 것이 아니다.
따라서 아래의 코드는 결국 error를 띄운다.
// Person Constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Greeting
Person.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName}`;
}
// Customer constructor
function Customer(firstName, lastName, phone, membership) {
Person.call(this, firstName, lastName);
this.phone = phone;
this.membership = membership;
}
// Create customer
const customer1 = new Customer("Tom", "Smith", "555-555-5555", "Standard");
console.log(customer1.greeting()); // error
이 문제를 해결하려면 중간에 다음의 코드를 필요로 한다. Customer의 프로토타입을 Person으로 설정하였기 때문에 Person이 Customer의 constructor를 가지고 있지 않다. 그래서 밑에 따로 Customer의 constructor를 설정해 준 것이다.
// Inherit the Person prototype methods
Customer.prototype = Object.create(Person.prototype);
// Make customer.prototype return Customer()
Customer.prototype.constructor = Customer;
상속된 메서드를 오버라이드 하는 것도 아래와 같이 가능하다.
// override greeting method
Customer.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName}. Welcome to our company!`;
}
상속이 완료된 최종코드는 아래와 같다.
// Person Constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Greeting
Person.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName}`;
}
const person1 = new Person("jian", "dev");
// Customer constructor
function Customer(firstName, lastName, phone, membership) {
Person.call(this, firstName, lastName);
this.phone = phone;
this.membership = membership;
}
// Inherit the Person prototype methods
Customer.prototype = Object.create(Person.prototype);
// Make customer.prototype return Customer()
Customer.prototype.constructor = Customer;
// Create customer
const customer1 = new Customer("Tom", "Smith", "666-555-5555", "Standard");
console.log(customer1);
console.log(customer1.constructor);
// override greeting method
Customer.prototype.greeting = function () {
return `Hello there ${this.firstName} ${this.lastName}. Welcome to our company!`;
}
console.log(customer1.greeting());