종우의 컴퓨터 공간

Prototypes Inheritance 본문

자바 스크립트 (JavaScript)/Object Oriented JavaScript - ES5&ES2015

Prototypes Inheritance

종우공간 2021. 8. 7. 13:55

예제

// Person constructor
function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

// Greeting in prototype
Person.prototype.greeting = function() {
    return `Hello there ${this.firstName} ${this.lastName}`;
}

// Create Person
const person1 = new Person('John', 'Doe');

console.log(person1);

// 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', '801-555-5555', 'Standard');

// Customer greeting(overriding)
Customer.prototype.greeting = function() {
    return `Hello there ${this.firstName} ${this.lastName}. welcome to our company`;
}

console.log(customer1);

console.log(customer1.greeting());

- Person.call()에서 call()은 이미 할당되어있는 다른 객체의 함수/메소드를 호출하는 해당 객체에 재할당할때 사용된다. this는 현재 객체(호출하는 객체)를 참조한다. 메소드를 한번 작성하면 새 객채를 위한 메소드를 재작성 할 필요 없이 call()을 티용해 객체에 상속할 수 있다.

- 프로토타입 메소드를 상속하는 코드랑 자기자신의 프로토타입을 리턴하게 하는 코드가 중요하다.

- Person 프로토타입 객체와 연결하면서도 컨스트럭터는 자기 자신꺼를 다시 가지도록 한다. 그래서 Customer 프로토타입 객체도 원형 객체가 될 수 있도록 한다. 그리고 new 연산자를 통해서 객체를 생성할 수 있도록 가능하게도 한다.