[JS] Javascript로 Class 구현해 상속받기
Javascript 2.0 spec에는 Class와 Interface가 지원된다지만.. 아직 대부분 브라우저들이 지원을 안하고 있습니다.

따라서 기존 Javascript로 Class와 상속을 구현해 보도록 하겠습니다. (IE, 모질라 다 됩니다.)

 function BaseClass () {
this.name = "base name";
this.type = "base type";
this.Run = function () {
alert("Run Base = " + this.name);
}
this.Exec = function () {
alert("Exec Base = " + this.name);
}
}






function SubClass () {
this.base = new BaseClass();
this.name = "sub name";
this.Run = function () {
alert("Run Sub = " + this.name);
this.base.Run();
}
}


SubClass.prototype = new BaseClass();
var a = new SubClass();
alert(a.name); // print "sub name"
alert(a.type); // print "base type"
a.Run(); // print "Run Sub = sub name" , "Run Base = base name"
a.Exec(); // print "Exec Base = sub name"

클래스 구현 방법이 여러가지 있지만
개인적으로 상속구조를 위해선 위의 방법이 가장 심플하고 의도한대로 출력값이 나오는 것 같습니다.
(단 a.Run();에서 "Run Base = base name" 대신 "Run Base = sub name"이 출력되는 결과였음 더 좋을뻔 했습니다..)

그럼 이만~


================================================================================================================
더 확실한 상속을 위해 상속 메소드를 만들어봤습니다. 상위클래스의 메소드를 호출할땐 함수명 앞에 $만 붙여주면 됩니다.


function Base(){
this.name = "base";
this.type = "human";
this.getName = function () {
return this.name + " is base";
}
}
function Child(){
this.name = "child";
this.getName = function () {
this.name = "child2";
return this.name + " " + this.$getName() + " " + this.type;
}
}
function Extend(child, base) {
child.prototype = new base(); //상속
var objBase = new base();
var objChild = new child(); //base 객체 생성
for(var item in objBase) {
if(typeof(objBase[item]) == "function")
objChild["$" + item] = objBase[item];
}
return objChild;
}
var obj = Extend(Child, Base);
alert(obj.getName());
//alert : child2 child2 is base human....

이 글과 관련있는 글을 자동검색한 결과입니다 [?]

by 귀뫄뉘 | 2008/01/11 11:48 | ┣ programming | 트랙백 | 덧글(2)
트랙백 주소 : http://kuimoani.egloos.com/tb/1272779
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
Commented at 2008/02/08 15:18
비공개 덧글입니다.
Commented by 귀뫄뉘 at 2008/02/09 12:02
아뇨.. 말그대로 interface요.. class에 inherit은 당연한거고.. interface상속으로 추상클래스(?) 상속도 된다고 하더라구요..^^ 모질라계열엔 이미 JS2.0 core가 들어갔다는데.. 언제쯤 보편화되련지..ㅎㅎ

:         :

:

비공개 덧글