자바스크립트 기본 - 상속
상속 - https://opentutorials.org/course/743/6572
상속(inheritance)이란 원래객체가 가지고 있는 기능을 상속받는 객체가 사용할 수 있다는 뜻이다.
자바스크립트에서 상속의 사용법을 알 수 있는 예제이다.(->이렇게 사용하면 상속이되는구나 라고 이해하는 예제)
이예제는 부모객체와 자식객체의 기능이 같은 예제이다.
function Person(name){
this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
return 'My name is '+this.name;
}
function Programmer(name){ //Programmer생성자를 만들었다.
this.name = name;
}
Programmer.prototype = new Person(); //Person이 객체가 되면서 Person이 가지고 있는 Person.prototype.name, Person.prototype.introduce을 포함하는 어떠한 객체가 만들어진다. 어떠한 객체는 Programmer.prototype에 담아진다.
상속이 이루어지는 곳이다.
var p1 = new Programmer('egoing'); //Programmer에 new를 붙여 객체로 만든다음 egoing을 인자로주었기 때문에 this.name=egoing이 된다. p1에는 this.name=egoing이라는 객체를 담는다.
document.write(p1.introduce()+"<br />");
예제는 자식객체가 부모객체의 기능을 물려받고 부모객체의 기능을 제외한 추가적인 기능을 가지는 방법이다.
function Person(name){
this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
return 'My name is '+this.name;
}
function Programmer(name){
this.name = name;
}
Programmer.prototype = new Person(); //이부분에서 상속이 되어진다.
Programmer.prototype.coding = function(){ //Programmer(자식객체)에 coding을 추가하였다.
return "hello world";
}
function Designer(name){
this.name = name;
}
Designer.prototype = new Person(); //이부분에서 상속이 되어진다.
Designer.prototype.design = function(){ //Designer(자식객체)에 design을 추가하였다.
return "beautiful!";
}
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");
var p2 = new Designer('leezche');
document.write(p2.introduce()+"<br />");
document.write(p2.design()+"<br />");
Person부모객체에서 Programmer자식객체과 Designer자식객체에게 자신의 기능을 상속하여준다.
Person부모객체에서 prototype의 return값을 변경하면 자식객체의 값에도 영향을 미친다.