2008년 06월 11일
다언어주의- javascript prototype
dW에서 재미난 글이 있어서, 업무시간에 짬을 내어 Javascript - prototype을 이용해서 구현해 보았다. 그냥 javascript으로만 구현하게되면 문법이 정갈하지 못하는데, prototype framework을 쓰게 되면 객체 생성이나 상속을 보기 좋게 할수 있어, prototype기반으로 작성하게 되었다. 스크립트 언어답게 특별한 인터페이스를 쓰지 않아도, 암묵적으로 다형성을 지원할 수 있다. 마지막 ShapeTest 클래스에서 [] 를 이용해 각각 Rectangle과 Circle의 인스턴스를 저장하였는데, each메소드를 이용해 일괄적으로 꺼내고, draw를 호출할수 있다. 특히 $super라는 메소드로 javascript에서 상위 클래스 메소드를 호출하게 할수 있는것을 볼수 있다.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>초보 개발자 코드 트레이닝, Part 1: 다언어주의 - Javascript prototype</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>
<script type="text/javascript">
var AbstractShape = Class.create({
initialize : function(x, y) {
this.x = x;
this.y = y;
},
draw : function() {
return this.toString();
},
moveTo : function(x, y) {
this.x = x;
this.y = y;
},
moveBy : function(x, y) {
this.x += x;
this.y += y;
},
toString : function() {
return new Template('[offset : #{x}, #{y}]').evaluate(this);
}
});
var Rectangle = Class.create(AbstractShape, {
initialize : function($super, x, y, width, height) {
$super(x,y);
this.width = width;
this.height = height;
},
draw : function() {
return this.toString();
},
toString : function($super) {
return $super() + new Template('[width: #{width}, height: #{height}] is Rectangle').evaluate(this);
}
});
var Circle = Class.create(AbstractShape, {
initialize : function($super, x, y, radius) {
$super(x, y);
this.radius = radius;
},
draw : function() {
return this.toString();
},
toString : function($super) {
return $super() + new Template('[radius: #{radius}] is Circle').evaluate(this);
}
});
var ShapeTest = Class.create({
initialize : function() {
this.shapes = [new Rectangle(0,0,10,15), new Circle(10,10,5)];
},
run : function() {
var result = [];
var g = this;
this.shapes.each(function(shape) {
result.push(g.doPolymorphicOp(shape).join('\r\n'));
});
alert(result.join("\r\n ------------ \r\n"));
},
doPolymorphicOp : function(shape) {
var result = [];
result.push(shape.draw());
shape.moveBy(10, 20);
result.push(shape.draw());
shape.moveTo(100, 130);
result.push(shape.draw());
return result;
}
});
new ShapeTest().run();
</script>
</head>
<body>
</body>
</html>
# by | 2008/06/11 14:26 | 객체지향 | 트랙백(1) | 핑백(1) | 덧글(1)






☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
제목 : 소내기의 생각
소내기 블로그 : 다언어주의- javascript prototype 10만년만의 블로그 포스팅, prototype으로 구현한 다형성입니다....more
... 초보 개발자 코드 트레이닝, Part 2: 알고리즘과 성능 이전 포스트에 이어서 또 퀴즈를 풀어보았습니다. Quiz 1,2는 다른 사람들도 모두 풀었던 관계로 생략합니다. 예제속에 답이 있어서 좀싱거운듯. Quiz 3, 4를 이어서 풀었는데, ... more
이부분에 오해의 소지가 있네요. ^^;
Javascript 는 Prototype-based (OOPL 또는) Language 입니다.
Javascript: The Definitive Guide 5/e 가 한역되었는데 꼭 읽어보시길 강추드립니다. ^^;
꾸벅~!