Skip to main content

Closure와 lambda 설명

ㅇ Closure lambda 차이
- lambda : 익명 함수
- Closure : 자신의 정의된 영역의 변수를 에워싸고(close over) 있는 것.
또는, 자신이 정의된 영역의 변수에 접근할 수 있는 것.
Closure를 사용하기 위해서 lambda(익명함수)가 사용됨

ㅇ Closure설명

https://docs.google.com/viewer?a=v&pid=forums&srcid=MTg0MjU3MDM2ODU0NjA0MzI4MzgBMTU5MDc0MTU3NDM3MzU5MTIwMjEBUUI4NE5VVjlFLVVKATQBAXYy

lambda는 람다 표현식 또는 람다 함수, 그리고 이름 없는 함수(anonymous function)라고 불리우며,
그 성질은 "함수 객체(functor)와 동일하다" 할 수 있다.

// Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
 if (sale.getCar().getBrand().equals("Hyundai")) {
 salesOfAHyundai.add(sale);
 }
}

// Functional version  => lambda 표현식
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")

ㅇ javascript Closure설명
=> lambda : 익명함수

function exampleClosureForm(arg1, arg2){
    var localVar = 8;
    function exampleReturned(innerArg){
        return ((arg1 + arg2)/(innerArg + localVar));
    }
    /* return a reference to the inner function defined as -
       exampleReturned -:-
    */
    return exampleReturned;
}

var globalVar = exampleClosureForm(2, 4);

ㅇ 클로저 용도

1)  클로저를 사용하는 가장 일반적인 용도는 함수를 실행하기에 앞서 함수 실행에 필요한 인자를 제공하는 것이다.

function callLater(paramA, paramB, paramC){
   return (function(){
       paramA[paramB] = paramC;
   });
}

var functRef = callLater(elStyle, "display", "none");
hideMenu = setTimeout(functRef, 500);

2) 함수와 객체 인스턴스 메소드 연결 ( Associating Functions with Object Instance Methods )

function associateObjWithEvent(obj, methodName){
   return (function(e){
       e = e||window.event;
       return obj[methodName](e, this);
   });
}

function DhtmlObject(elementId){
   var el = getElementWithId(elementId);
   if(el){
       el.onclick = associateObjWithEvent(this, "doOnClick");
   }
}
DhtmlObject.prototype.doOnClick = function(event, element){
   ... // doOnClick method body.
}

3) 관계된 함수의 캡슐화 ( Encapsulating Related Functionality )

var getImgInPositionedDivHtml = (function(){
   var buffAr = [
       '<div id="',
       '',   //index 1, DIV ID attribute
       '" style="position:absolute;top:',
       '',   //index 3, DIV top position
       'px;left:',
       '',   //index 5, DIV left position
       '\"><\/div>'
   ];
   return (function(url, id, width, height, top, left, altText){
       buffAr[1] = id;
       buffAr[3] = top;
       buffAr[5] = left;
       return buffAr.join('');
   }); //:End of inner function expression.
})();


Comments

Popular posts from this blog

Amazon RDS Blue/Green Deployments

In order to avoid some errors I experienced when proceeding as described in the official documentation, I describe what I did in order. 1) Modify parameters of source_database * error: Blue Green Deployments requires cluster parameter group has binlog enabled. RDS Parameter groups: source-params-group binlog_format => MIXED mysql> show global variables like 'binlog_format'; 2) Insert a row after rebooting the source database, to avoid this error. * error: Correct the replication errors and then switch over. Read Replica Replication Error - IOError: 1236, reason: Got fatal error 1236 from master when reading data from binary log: 'Could not find first log file name in binary log index file' => To Fix: You need to change the data in the source database. INSERT INTO dummy_table ( `favorite_id` , `favorite_order` , `user_id` , `board_id` ) VALUES ('100001', '1', '11111', '11111'); 3) Modify the param...

Fluentd for mysql in AWS

(0) preparation ulimit -n If your console shows 1024, it is insufficient. Please add following lines to your /etc/security/limits.conf file and reboot your machine. root soft nofile 65536 root hard nofile 65536 (1) install Fluentd // “Ubuntu 12.04 LTS / Precise” curl -L http://toolbelt.treasuredata.com/sh/install-ubuntu-precise.sh | sh /etc/init.d/td-agent start/stop/restart/status // test curl -X POST -d 'json={"json":"message"}' http://localhost:8888/debug.test /etc/init.d/td-agent stop chown: changing ownership of `/var/run/td-agent/td-agent.pid': Operation not permitted chown: changing ownership of `/var/run/td-agent': Operation not permitted  * Stopping td-agent td-agent                                                                                   ...

Install CoreOs on linode without VM

Install CoreOs on linode without VM 1. Add a Linode 2. Create a new Disk   CoreOS 3. Rescue > Reboot into Rescue Mode 4. Remote Access   Launch Lish Console 5. make an install script cat <<'EOF1' > install.sh # add needed package sudo apt-get update sudo apt-get install -y curl wget whois sudo apt-get install -y ca-certificates #sudo apt-get install gawk -y # get discovery url discoveryUrl=`curl https://discovery.etcd.io/new` # write cloud-config.yml cat <<EOF2 > cloud-config.yml #cloud-config users:   - name: core     groups:       - sudo       - docker coreos:   etcd:     name: node01     discovery: $discoveryUrl hostname: node01 EOF2 # get the coreos installation script #wget https://raw.github.com/coreos/init/master/bin/coreos-install wget https://raw.githubusercontent.com/coreos/init/master/bin/coreos-install # run installation chmod 75...