2007/11/22

Javascript 간이 closure

a=[10,3,7,12,1,43]
10,3,7,12,1,43
a.sort()
1,10,12,3,43,7
[10, 3, 7, 12, 1, 43].sort()
1,10,12,3,43,7
------------------------
Array.prototype.map=function(f) { var result=[]; for (i in this) result[i]=f(this[i]); return result; }
function (f) { var result = []; for (i in this) { result[i] = f(this[i]); } return result; }
[1,2,3,4,5].map(function(x) { return x*x })
1,4,9,16,25
[10, 3, 7, 12, 1, 43].sort().map(function(x) {return x*x })
1,100,144,9,1849,49
[10, 3, 7, 12, 1, 43].sort().map(function(x) {return x*x }).sort()
1,100,144,1849,49,9

인자가 n개일땐 어떨지 모르겠다.

Javascript 연습 - 배열은 객체다?/Prototype을 통한 Native 확장

파란색 글자를 따라가면서 한줄한줄 쳐봅시다.
줄바꿈은 Shift+Enter 사용하면 됩니다.
Javascript Shell 이쪽에서 IE/FF 골라봅니다. FF 추천!
  • // function 이해
a=' fccc sad fwe '
fccc sad fwe
괄호만들기=function(x){return '('+x+')'}
function (x) { return "(" + x + ")"; }
괄호만들기(a)
( fccc sad fwe )
제품['상품명']=' 야매너구리 '
ReferenceError on line 1: \uC81C\uD488 is not defined
제품=[]
제품['상품명']=' 야매 너구리 '
야매 너구리
제품['포장']=function() { return '('+this['상품명']+')' }
function () { return "(" + this.\uC0C1\uD488\uBA85 + ")"; }
제품.포장
function () { return "(" + this.\uC0C1\uD488\uBA85 + ")"; }
제품.포장()
( 야매 너구리 )

  • // Trim 만들고 Prototype 에 확장
' 야메 너구리 '.replace(/^\s*|\s*$/g,'')
야메 너구리
'@@'+' 야메 너구리 '.replace(/^\s*|\s*$/g,'')+'@@'
@@야메 너구리@@
String.trim=function() {return this.replace(/^\s*|\s*$/g,'')}
function () { return this.replace(/^\s*|\s*$/g, ""); }
a=' 야메 '
야메
a.trim()
TypeError on line 1: a.trim is not a function
String.prototype.trim=function() {return this.replace(/^\s*|\s*$/g,'')}
function () { return this.replace(/^\s*|\s*$/g, ""); }
a.trim()
야메
'@@'+a.trim()+'@@'
@@야메@@
'@@'+' 야매 '.trim()+'@@'
@@야매@@
  • for x in z 를 이용한 심화 예제, type 알아보기
// 배열에 있는 값들을 합치는 method를 만들어봅니다.
Array.prototype.sum=function() { for (x in this) result+=x; return result; }
function () { for (x in this) { result += x; } return result; }
a=[1,2,3,4,5,6]
1,2,3,4,5,6
a.sum()
ReferenceError on line 2: reference to undefined property "result"
// 아무리 타입캐스팅이 관대하지만 좀 너무 했습니다. 초기화 정도는 해줍시다.
Array.prototype.concats=function() { var result=''; for (x in this) result+=x; return result; }
function () { var result = ""; for (x in this) { result += x; } return result; }
a.concats()
012345sumconcats
// 오류를 발견했습니다. 첫째로는 값을 가져와야하는데 키를 가져왔고 method 명까지 같이 나와버렸습니다.
props(a)
Fields: 0, 1, 2, 3, 4, 5
Methods of prototype: concats, sum
// Shell 내장함수인 props 는 필드와 Method 를 구분합니다. 어떻게 할까요?
props
function props(e, onePerLine) { if (e === null) { println("props called with null argument", "error"); return; } if (e === undefined) { println("props called with undefined argument", "error"); return; } var ns = ["Methods", "Fields", "Unreachables"]; var as = [[], [], []]; var p, j, i; var protoLevels = 0; for (p = e; p; p = p.__proto__) { for (i = 0; i < protolevel =" -1;" p =" e;" p =" p.__proto__)" protolevel =" 0;" type =" 1;" style="color: rgb(255, 0, 0);">typeof e[a] == "function") { type = 0; } } catch (er) { type = 2; } as[type][protoLevel].push(a); } function times(s, n) { return n ? s + times(s, n - 1) : ""; } for (j = 0; j < i =" 0;">
// 호오 typeof e[a] == "function" 이 부분이 눈에 들어오는군요
a
1,2,3,4,5,6
props(a)
Fields: 0, 1, 2, 3, 4, 5
Methods of prototype: concats, sum
typeof a['concats']
function
typeof a['0']
number
Array.prototype.concats=function() { var result=''; for (x in this) result+= typeof this[x]=='function' ? '' : this[x]; return result; }
function () { var result = ""; for (x in this) { result += typeof this[x] == "function" ? "" : this[x]; } return result; }
a.concats()
123456
a
1,2,3,4,5,6
a=['이','사','육','팔','십']
이,사,육,팔,십
a.concats()
이사육팔십


수고하셨습니다 :)