본문 바로가기
카테고리 없음

Javascript로 Class 만들기2

by 철이아부지 2014. 12. 11.

그냥 Object로 만들었더니 instanceof 에 anonymous로 잡히고.. 여러 문제도 있어서

전역 변수로 클래스들을 관리하며 prototype을 사용하는 새로운 클래스 함수를 만들어봤습니다.

사용법은 거의 같으나 클래스를 굳이 변수에 담을 필요 없고 init 대신에 클래스 이름이 생성자가 됩니다.

클래스 상속시 상위 클래스의 생성자는 인자 없이 호출됩니다. 따라서 아래 예제 처럼 상위 생성자에 인자를 전달하려면 생성자 내부에서 다시 호출하여 주면 됩니다.

상위 클래스의 method 호출을 위한 superCall 기능도 추가되었습니다.

사용 예제 입니다.

0.2 에서 static 기능이 추가되었습니다.


jj.Class( 'Fruit', {

color: '',

name: '',

Fruit: function( name, color ) {

this.name = name;

this.color = color;

},

getName: function() {

return this.name;

},

getColor: function() {

return this.color;

}

});

jj.Class( 'Apple', {

Apple: function() {

this.Fruit('Apple', 'Red');

}

}, 'Fruit');

jj.Class( 'Pear', {

Pear: function() {

this.Fruit('Pear', 'Yellow');

jj.Pear.add();

},

getName: function() {

return 'Sweet ' + this.superCall('Fruit', 'getName');

}

}, 'Fruit').static( {

count: 0,

add: function() {

this.count++;

},

getCount: function() {

return this.count;

}

});

var orange = new jj.Fruit('Orange', 'Orange');

var pear = new jj.Pear();

var pear2 = new jj.Pear();

var pear3 = new jj.Pear();

var apple = new jj.Apple();

$(function() {

var html = orange.getName() + '\'s color is ' + orange.getColor() + '</br>';

html += apple.getName() + '\'s color is ' + apple.getColor() + '</br>';

html += pear.getName() + '\'s color is ' + pear.getColor() + '</br>';

html += 'Pear counter is ' + jj.Pear.getCount() + '</br>';

$('#output').html(html);

});

자바 스크립트와 샘플을 첨부 합니다. jquery는 예제때문에 들어간것이고 jjlib 자체는 jquery에 의존성이 없습니다.


jjlib.0.2.zip