function Dog(name, emoji){
this.name = name;
this.emoji = emoji;
//인스턴스 레벨의 함수
// this.printName = () => {
// console.log(`${this.name} ${this.emoji}`);
// };
}
//프로토타입 레벨의 함수
Dog.prototype.printName = function() {
console.log(`${this.name} ${this.emoji}`);
};
const dog1 = new Dog('뭉치', '🐶');
const dog2 = new Dog('코코', '🐱');
console.log(dog1, dog2);
dog1.printName();
dog2.printName();
- 오버라이딩
- 인스턴스 레벨에서(자식) 동일한 이름으로 함수를 재정의 하면(오버라이딩 하면)
- 프로토타입 레벨의(부모) 함수의 프로퍼티는 가려진다(새도잉 됨)
dog1.printName = function () {
console.log('안녕!');
}
dog1.printName();
//정적 레벨
Dog.hello = () => {
console.log('Hello!');
};
Dog.hello();
Dog.Max_AGE = 20;
- 프로토타입을 베이스로 한 객체지향 프로그래밍
- html 문서를 만들어 script 링크를 해준 후, live stream을 통해 콘솔창에서 보면, 객체의 상속을 확인할 수있음
function Animal(name, emoji) {
this.name = name;
this.emoji = emoji;
}
Animal.prototype.printName = function () {
console.log(`${this.name} ${this.emoji}`);
};
function Dog(name, emoji, owner){
// super(name, emoji);
Animal.call(this, name, emoji);
this.owner = owner;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.play = () => {
console.log('갈이 놀자옹!');
};
function Tiger(name, emoji){
Animal.call(this, name, emoji);
}
Tiger.prototype = Object.create(Animal.prototype);
Tiger.prototype.hunt = () => {
console.log('사냥하자..🐇..');
}
const dog1 = new Dog('멍멍', '🐶', '엘리');
dog1.play();
dog1.printName();
const tiger1 = new Tiger('어흥', '🐯');
tiger1.prinName();
tiger1.hunt();
console.log(dog1 instanceof Dog);
console.log(dog1 instanceof Animal);
console.log(dog1 instanceof Tiger);
console.log(tiger1 instanceof Dog);
console.log(tiger1 instanceof Animal);
console.log(tiger1 instanceof Tiger);
- class를 사용하여 prototype의 번잡함을 날려버리기!
class Animal{
constructor(name, emoji){
this.name = name;
this.emoji = emoji;
}
printName() {
console.log(`${this.name} ${this.emoji}`);
}
}
class Dog extends Animal {
play () {
console.log('갈이 놀자옹!');
}
}
class Tiger extends Animal{
hunt () {
console.log('사냥하자..🐇..');
}
}
const dog1 = new Dog('멍멍', '🐶', '엘리');
const tiger1 = new Tiger('어흥', '🐯');
dog1.printName();
tiger1.printName();
dog1.play();
tiger1.hunt();
console.log(dog1 instanceof Dog);
console.log(dog1 instanceof Animal);
console.log(dog1 instanceof Tiger);
console.log(tiger1 instanceof Tiger);