Language/JavaScript

[JavaScript] 상속

jaewpark 2021. 10. 10. 13:07

상속

객체의 로직을 그대로 물려받는 또 다른 객체를 만들 수 있는 기능

 

아래와 같은 코드가 있으면,

1
2
3
4
5
6
7
8
function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
cs

 

prototype을 통해서 상속을 할 수 있다.

1
2
3
4
5
6
7
8
9
function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
cs

 

또한, 아래의 코드에서 Programmer는 Person의 기능을 가지고 있으면서,

메소드 coding 또한 가지고 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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(){
    return "hello world";
}
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");
cs

 

속성을 사용하기 위한 Prototype

 

1
2
3
4
5
6
7
8
9
10
11
function Ultra(){}
Ultra.prototype.ultraProp = true;
 
function Super(){}
Super.prototype = new Ultra();
 
function Sub(){}
Sub.prototype = new Super();
 
var o = new Sub();
console.log(o.ultraProp);
cs

o.ultraProp 이라는 걸 찾기 위해서, 객체 o에서 찾고 없다면

Sub.portotype.ultraProp을 찾는다. 없다면 Super에서, Ultrea까지 찾게 되는 것이다.

객체와 객체를 연결하는 체인역할을 하는 prototype이기에 가능하다.

 

prototype에 대한 이해를 높이기 위해서는 아래의 링크를 이용

Prototype 이해