Written by
JJoo
on
on
상속의 개념
객체의 기본 형태
부모에게 있는 변수와 메소드를 똑같이 물려받아 부모 객체의 기능을 그대로 동일하게 사용할 수 있다.
상속이란 (Inheritance)
부모의 기능 중 필요한 기능만 불러와 재활용 할 수 있다. 로직을 재활용할 수 있다.
부모의 기능을 가져와서 재활용하고, 자신의 기능을 발전시킬 수 있는 것이 상속이다.
Prototype 사용
Prototype을 사용하면 객체에 해당 값이 없어도 prototype에서 그 값을 찾는다.
function Fruit(name){
this.name = name;
}
Fruit.prototype.name=null;
Fruit.prototype.intro = function(){
return 'This is ' + this.name;
}
function apple (name){
this.name = name;
}
apple.prototype = new Fruit();
const redApple = new apple('apple');
document.write(redApple.intro())
결과
This is apple
apple
에는 intro()
가 없지만 prototype
으로 상속된 부모 Fruit
에 intro()
있기때문에 intro()
를 사용할 수 있다.
function Fruit(name){
this.name = name;
}
Fruit.prototype.name=null;
Fruit.prototype.intro = function(){
return 'This is ' + this.name;
}
function apple (name){
this.name = name;
}
apple.prototype = new Fruit();
apple.prototype.color = function(color){
this.color = color;
return 'color is ' + this.color;
}
function banana (name){
this.name = name;
}
banana.prototype = new Fruit();
banana.prototype.size = function(size){
this.size = size;
return 'size is ' + this.size;
}
const redApple = new apple('redApple');
const greenApple = new apple('greenApple');
const longBanana = new banana('longBanana');
document.write(redApple.intro()+"<br />");
document.write(redApple.color('red')+"<br />");
document.write(greenApple.intro()+"<br />");
document.write(greenApple.color('green')+"<br />");
document.write(longBanana.intro()+"<br />");
document.write(longBanana.size('long')+"<br />");
결과
This is redApple
color is red
This is greenApple
color is green
This is longBanana
size is long
Fruit
이라는 공통의 부모가 되는 객체가 있고
Fruit
를 부모로 가지고 있는 apple
과 banana
가 있고,
apple
을 부모로 하는 redApple
과 greenApple
과
banana
를 부모로 하는 longBanana
가 있다.
Fruit
의 기능을 공통으로 가질 수 있고
apple
에는 color
, banana
에는 size
같은 각각의 특징을 지정할 수도 있다.
상속에서 중요한 개념이 prototype!!
Discussion and feedback