➡️ 원형객체 (original form)
자바스크립트에는 class의 개념이 없었다.
대신 prototype이 존재하며, 자바스크립트는 prototype 기반 언어라고 불린다. class가 없으니 prototype을 기반으로 상속을 구현하여 사용해 왔다.
ES6 표준에서 class 문법이 추가되었으나, 자바스크립트가 class기반으로 바뀌어다는 것은 아니다.
모든 객체의 상위 객체는 Object 이다.
( toString()을 작성하지 않아도 모근 객체에서 사용할 수 있는 이유 ➡ 상속 !! )
상위 prototype 객체를 상속받은 하위객체는 그 하위객체에서 또 상속받고, 이렇게 상속되는 일이 반복된다. 이렇게 서로 연결되어 있는 것을 prototype chain이라고 한다.
prototype 연습
let Common = function (name) {
this.name = name; // property 생성
this.color = 'green';
}
// Common -> prototype 형성
Common.prototype.ethnic = function () { // method
return `${this.name} is from Korea`;
}
let hyunsoo = new Common('Hyunsoo'); // 생성자함수 new Common()의 instance
let Person = function (name) {
Common.call(this, name);
this.sports = 'free diving';
this.coffee = 'latte';
}
// Person의 method를 Object.create하기 전에 생성해 버리면,
// 연결이 되지 않아 나중에 생성자 함수 new()를 만들었을때,
// 이 부분은 실행되지 않음 => constructor 연결 후에 작성!!
// Person.prototype.quote = function () {
// return 'Rather be dead than cool';
// }
Person.prototype = Object.create(Common.prototype);
Person.prototype.constructor = Person;
Person.prototype.quote = function () {
return 'Rather be dead than cool';
}
let heeni = new Person('Heeni');
class 연습
class Common {
constructor(name) {
this.name = name;
this.color = 'green';
}
ethnic() {
return `${this.name} is from Korea`;
}
}
let hyunsoo = new Common('Hyunsoo');
class Person extends Common {
constructor(name) {
super(name);
this.sports = 'free diving';
this.food = 'kimchi';
}
quote() {
return 'Rather be dead than cool';
}
}
let heeni = new Person('Heeni');