2016年4月23日土曜日

Javascriptでクロージャ

PythonによるWebスクレイピング P154を読んでいたら こんなjavascriptのスクリプトが出てきた。

<script>
var fibonacci=function(){
 var a=1;
 var b=1
 return function(){
  var temp=b;
  b=a+b;
  a=temp;
  return b;
 }
}

var fibInstance=fibonacci();
console.log(fibInstance()+" is in the Fibonacci sequence");
console.log(fibInstance()+" is in the Fibonacci sequence");
console.log(fibInstance()+" is in the Fibonacci sequence");
console.log(fibInstance()+" is in the Fibonacci sequence");
console.log(fibInstance()+" is in the Fibonacci sequence");
</script>


○ 参考までに、プログラミングF# P55にクロージャの例としてこういうのがのっていた。
>let gereratePowerOfFunc baseValue=(fun exponent -> baseValue ** exponent);;
>let powerOfTwo=generatePowerOfFunc 2.0;;
>powerOfTwo 8.0;;
 val it:float =256.0
2.0がどこに保持されているか。。値がスコープ内にあれば、その値を使用でき、またその値も関数によって返されることがある。

P209では、クロージャとは、内部あるいはネストされた関数において、関数に引数を明示的に指定せずとも何らかの値にアクセスできることを表す用語です。...
 >let mult i lst=List.map(fun x->x*i) lst;;
    val mult: int -> int list -> int list
  >mult 10 [1;3;5;7];;
    val it:int list=[10;30;50;70]



 

0 件のコメント:

コメントを投稿