Closure

Closure의 의미와 타 언어와의 차이점

1.
enclosing 영역의 variable 을 closure 내에서 참조할 수 있음
즉, closure가 정의되는 시점에서 바깥의 변수를 참조할 수 있음
함수포인터(C), anonyouse inner class(Java), delegate(C#) 는 이렇게 할 수 없음
(Java의 경우 final 일 때만 local 변수에 접근 가능)
def highPaid(emps)
threshold = 150
return emps.select {|e| e.salary > threshold} #threshold 를 참조할 수 있음
end

2.
변수처럼 인자로 전달하거나 리턴값으로 반환할 수 있다.
def paidMore(amount)
return Proc.new {|e| e.salary > amount}
end
highPaid = paidMore(150)
john = Employee.new
john.salary = 200
print highPaid.call(john)


특징
1. 코드블럭이면서 정의된 시점의 환경에 대한 바인딩을 보존하고 있다. (환경에 대한 바인딩이란 변수 생존 영역을 뜻함)
(정의 시점의 환경변수들까지 가지고 있다가 나중에 실행시킬 수 있는 코드블럭 이라고 보면 됨)
A key property of closures is that they don't need to be executed when they are evaluated, they can be saved for later - even if they refer to variables that aren't in scope when the block is actually executed.
2. 단순문법으로 사용가능



소스 : Martin Fowler

by Augie | 2008/01/21 11:11 | 트랙백

트랙백 주소 : http://ironcpa.egloos.com/tb/3585689
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
※ 로그인 사용자만 덧글을 남길 수 있습니다.

◀ 이전 페이지          다음 페이지 ▶