웹표준,웹접근성(html, html5, css, css3, javascript, jQuery, jQueryMobile, snecha, senchaTouch, php, mobileWebApp)
상속 본문
상속
- 기존에 생성자함수 또는 객체를 기반으로 새로운 생성자 함수나 객체를 만들어 내는 것
- 부모 요소로 부터 속성과 메서드를 물려 받는 것
ex 1) 상속받기
// money 매개변수를 받는 Price 생성자 함수 생성
function Price(money){
// p 변수에 매개변수로 받은 money 저장
var p = money;
// 메서드 선언 , 결과값으로 p 를 리턴
this.getP = function(){ return p; };
}
// prototype공간에 getMoneyPlan메서드 선언
Price.prototype.getMoneyPlan= function(){
// getP 에 저장된 값을 12로 나눠서 결과값 리턴
return this.getP() / 12;
}
// money 매개변수를 받는 Genesis 생성자 함수 생성
function Genesis(money) {
// test 공간을 만들고 생성자 함수 Price를 담는다.
this.test = Price;
// Price함수를 받은 test 공간에 매개 변수로 money를 던진다.
this.test(money);
}
// Price의 prototype이 가지는 메서드를 genesis 에도 부여한다.
Genesis.prototype = Price.prototype;
// price 변수에 new 키워드를 사용 Price생성자 함수에 3000을 던진다.
var price = new Price(3000);
// genesis 변수에 new 키워드를 사용 Genesis 함수에 5000을 던진다.
var genesis = new Genesis(5000);
// 화면출력, price변수에 던진 매개변수를 바탕으로 getMoneyPlan 메서드 실행
console.log(price.getMoneyPlan());
// 화면출력, genesis 던진 매개변수를 바탕으로 getMoneyPlan 메서드 실행
console.log(genesis.getMoneyPlan());
// genesis객체가 Price 생성자 함수를 통해 먼들어 졋는지 확인
console.log(genesis instanceof Price);
ex 2) call() 메서드를 이용 상속받기
- 다른 객체의 메서드를 자신의 메서드 처럼 사용할 수 있게 하는 것
- 매개변수로 this 를 넘겨 줘야 함수 내부에서 자신이 누구인지 알수 있다.
// money 매개변수를 받는 Price 생성자 함수 생성
function Price(money){
// p 변수에 매개변수로 받은 money 저장
var p = money;
// 메서드 선언 , 결과값으로 p 를 리턴
this.getP = function(){ return p; };
}
// prototype공간에 getMoneyPlan메서드 선언
Price.prototype.getMoneyPlan= function(){
// getP 에 저장된 값을 12로 나눠서 결과값 리턴
return this.getP() / 12;
}
// money 매개변수를 받는 Genesis 생성자 함수 생성
function Genesis(money) {
// Price의 메서드를 콜 해 온다.
Price.call(this, money);
}
// Genesis의 prototype 에 생성자 함수 Price를 담는다.
Genesis.prototype = new Price();
// 복사해온 생성자함수를 Genesis 로 재정의 한다.
Genesis.prototype.constructor = Genesis;
// price 변수에 new 키워드를 사용 Price 함수에 3000을 던진다.
var price = new Price(3000);
// genesis 변수에 new 키워드를 사용 Genesis 함수에 5000을 던진다.
var genesis = new Genesis(5000);
// 화면출력, price변수에 던진 매개변수를 바탕으로 getMoneyPlan 메서드 실행
console.log(price.getMoneyPlan());
// 화면출력, genesis 던진 매개변수를 바탕으로 getMoneyPlan 메서드 실행
console.log(genesis.getMoneyPlan());
// genesis객체가 Price 생성자 함수를 통해 먼들어 졋는지 확인
console.log(genesis instanceof Price);
'javascript > Tutorial' 카테고리의 다른 글
Object 객체 생성 및 메서드 (0) | 2014.01.07 |
---|---|
기본자료형과 객체의 차이점 (0) | 2014.01.07 |
instanceof (0) | 2013.12.11 |
new 키워드 (0) | 2013.12.11 |
생성자함수와 프로토타입 (0) | 2013.12.10 |