5월, 2013의 게시물 표시

자바스크립트 oop를 넘어 aop로

이 글을 어떻게 하면 객체지향을 넘어 관점지향 프로그래밍을 하는 방법에 대해서 기술한 것입니다. 우선 간단하게 객체지향에 대해서 알아보도록 하겠습니다. 객체지향프로그래밍은 영어로 Object-Oriented Programming 줄여서 OOP라고 합니다. 이것은 프로그래밍 패러다임의 일종으로써, 이전의 절차지향적 프로그래밍 이후에 나온 패러다임입니다. 간단하기 이야기 하자면 프로그래밍을 할때 주인공이 변경되었다라고 생각하시면 됩니다. 이전에는 함수(function)위주로 프로그래밍을 하였다면 이후에는 객체(object)위주로 프로그래밍을 한다는 의미 입니다. 즉 논리 보다는 다루고자 하는 객체라는 시각으로 접근하는 것입니다. ex> 절차 지향적 프로그래밍 숫자+숫자-숫자을 계산하는 프로그램을 구현하시오. function compute(a,b,c){ return a+b-c; } OOP관점에서는 obj = { a: 0, b: 0, c: 0, init: function(a,b,c){ this.a = a; this.b=b; this.c=c}, compute: function(){return this.a + this.b - this.c } obj.init(숫자, 숫자, 숫자); obj.compute(); 두 패러다임에서 누가 옳고 그르다고 말할 수 없습니다. 프로그램의 규모가 작은 경우 즉 위와 같은 경우에는 확실이 절차지향 프로그램이 이점을 가지고 있습니다. 하지만 애플리케이션 단위로 프로그램이 크다면 객체지향 프로그램이 더욱 더 좋은 선택이 될 것입니다. 현재 자바스크립트 소스코드는 절차지향적 프로그래밍 되어 있는것들이 많이 있습니다. 그 이유는 아마도 자바스크립트로 되어 있는 프로그램의 대부분이 소규모인 경우가 많아서 그런것이라고 생각합니다. 하지만 점점 웹의 규모가 커지고 사용자의 웹에대한 욕구가 커지면서 자바스크립트는 소규모를 넘는 프로그램을 할 필요성이 점점 증가하고 있습니다.

자바스크립트 prototype을 활용한 상속

(function ($_) { $_.Base = {}; function subclass() {}; var Class = function(/*parent, protoProps, staticProps*/) { var arg = $_.A.toArray(arguments), parent = null, protoProps, staticProps; if($_.O.isFunction(arg[0])) parent = arg.shift(); protoProps = arg[0]; staticProps = arg[1]; function child() { var self = this, key, arg = $_.A.toArray(arguments); for(key in self){ if(!$_.O.isFunction(self[key]))self[key] = $_.O.clone(self[key]); } function initsuper(parent) { if(!parent) return; if(parent.superclass) initsuper(parent.superclass); parent.prototype.initialize.apply(self, arg); } initsuper(parent); this.initialize.apply(this, arg); } child.superclass = parent; child.subclasses = []; if(parent){ subclass.prototype = parent.prototype; child.prototype = new subclass(); parent.subclasses.push(child); } child.prototype.initialize = function () {}; if (protoProps) $_.O.ext

jQuery를 응용한 소스

(function (definition) {     // RequireJS     if (typeof define == "function") {         define([Asdf], definition);     } else {         definition(Asdf);     } }) (function($_) { var arraySlice = Array.prototype.slice, readyRE = /complete|loaded|interactive/, isString = $_.O.isString ; var arrayMap =  $_.A.map, nativeSplice = Array.prototype.splice, extend = $_.O.extend; var root = this, compact = $_.A.compact; function El(){ if (this.constructor !== El){ return new El(); } }; function map(elements, fn){ return arrayMap(elements, function(el, i){ return fn.call(el, i, el); }); } function slice(elements){    return arraySlice.apply(toArray(elements), arraySlice.call(arguments,1)); } function toArray(elements) { var arr = []; for (var i = 0, ref = arr.length = elements.length; i < ref; i++) { arr[i] = elements[i]; } return arr; } function get(elements, idx){ return idx === undefined ? toArray(elements) : e