자바스크립트는 프로토타입 기반 언어라고 불립니다. 자바스크립트는 객체지향언어입니다. 그리고 class 라는 개념이 없어서 포로토타입으로 상속을 흉내내도록 합니다.
프로토 타입 기반 언어는 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들어 냅니다.
이렇게 생성된 객체 역시 또 다른 객체의 원형이 될 수 있습니다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound); // 월월, 미야아옹
};
Animal.prototype.sharedValue = 1;
const dog = new Animal('개', '멍멍이', '월월');
const cat = new Animal('고양이', '야옹이', '미야아옹');
dog.say();
cat.say();
console.log(dog.sharedValue); // 1
console.log(cat.sharedValue); // 2
Animal 이라는 클래스를 만들어서 say, sharedValue들을 Animal에서 상속받아서 훨씬 유용하게 사용하도록 합니다..
class Animal{
constructor(type, name, sound){// 객체 생성자
this.type = type;
this.name = name;
this.sound = sound;
}
say() { // say 라는 함수를 class 내부에 생성 자동으로 프로토타입으로 설정됨, 메서드
console.log(this.sound);
}
}
class Dog extends Animal{ // extends => 특정 클래스를 상속받는다.
constructor(name, sound) {
super('개', name, sound); // 자신이 상속받은 constructor 호출
}
}
class Cat extends Animal{ // extends => 특정 클래스를 상속받는다.
constructor(name, sound) {
super('고양이', name, sound);
}
}
console.log(Animal.prototype.say); // function say() {}
const dog = new Dog('개', '멍멍이', '월월');
const cat = new Cat('고양이', '야옹이', '미야오옹');
dog.say();
cat.say();
class Person {
constructor({name, age}) {
this.name = name;
this.age = age;
}
introduce() {
return `제 이름은 ${this.name} ${this.age}살입니다.`
}
}
class Student extends Person {
constructor({grade, ...rest}) {
// 부모 클래스의 생성자를 호출할 수 있습니다.
super(rest);
this.grade = grade;
}
introduce() {
// 부모 클래스의 `introduce` 메소드를 호출할 수 있습니다.
return super.introduce() + ` 저는 ${this.grade}학년입니다.`;
}
}
const s = new Student({grade: 1, name: '스폰지밥', age: 26});
s.introduce(); // 제 이름은 스폰지밥 26살입니다. 저는 1학년입니다.
class Person {}
class Student extends Person {};
class student = new Student;
부모의 기능을 복사한 새로운 객체를 생성한다.
const Car = function (color) {
this.color = color;
}
const car1 = new Car('red');
const car2 = Object.create(Car.prototype);
// console.dir(car1); // Car { color: 'red' }
// console.dir(car2) // Car {}
Car.prototype = {
getColor(){
return this.color;
}
};
const ToyCar = function() {
};
ToyCar.prototype = Object.create(Car.prototype);
const legoCar = new ToyCar()
console.dir(legoCar) // 1번사진 처럼 나온다.
console.dir(legoCar instanceof ToyCar);
console.dir(legoCar instanceof Car); // true 일까요 false 일까요?
console.dir(legoCar instanceof Object); // true 일까요 false 일까요?
console.dir(ToyCar.prototype.isPrototypeof(legoCar); // ???
출처: https://arabiannight.tistory.com/entry/301 [아라비안나이트]
1번사진