상속(prototype)

2016. 11. 27. 19:04Programming/JavaScript

상속은 propertype을 이용해 간단히 할 수 있다.


Programmer.prototype = new Person();



<예제>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Person 객체
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;
}
 
//프로그래머 생성, coding() 추가
Programmer.prototype = new Person();
Programmer.prototype.coding = function(){
    return "hello world";
}
 
//'egoing' 이름으로 p1 객체 생성
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");
document.write(p1.coding()+"<br />");
cs


<prototype의 원리>

객체 간의 정보 공유 chain을 형성한다.

객체 o > sub > super > ultra 순서대로 자원(ultraProp)을 찾을 수 있게 해준다.



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);//true가 출력
cs


<prototype의 다른 기능: 내장객체의 확장>

Array와 random을 한 객체에 담아서 이용할 수 있게 됨.


1
2
3
4
5
6
Array.prototype.random = function(){
    var index = Math.floor(this.length*Math.random());
    return this[index];
}
var arr = new Array('seoul','new york','ladarkh','pusan''Tsukuba');
console.log(arr.random());
cs


Object에 있는 메소드 사용도 가능


1
2
3
4
5
6
7
8
9
10
Object.prototype.contain = function(seoul) {
    for(var city in this){
        if(this[city] === seoul){
            return true;
        }
    }
    return false;
}
var o = {'name':'egoing''city':'seoul'}
console.log(o.contain('seoul'));//true 출력
cs






'Programming > JavaScript' 카테고리의 다른 글

Object Model(자바스크립트 개요), BOM, DOM  (0) 2016.11.28
AJAX 정리  (0) 2016.11.23
JSON 정리  (0) 2016.11.23
함수(Function)  (0) 2016.11.23
문자열, 배열 처리  (0) 2016.11.22