JavaScript闭包参数

时间:2017-02-17 03:55:32

标签: javascript

foo等于iCantThinkOfAName,但iCantThinkOfAName有两个参数,foo只有一个参数。我不明白foo(2)如何返回num: 4

function iCantThinkOfAName(num, obj) {
  // This array variable, along with the 2 parameters passed in, 
  // are 'captured' by the nested function 'doSomething'
  var array = [1, 2, 3];

  function doSomething(i) {
    num += i;
    array.push(num);
    console.log('num: ' + num);
    console.log('array: ' + array);
    console.log('obj.value: ' + obj.value);
  }
  return doSomething;
}
var referenceObject = {
  value: 10
};
var foo = iCantThinkOfAName(2, referenceObject); // closure #1
var bar = iCantThinkOfAName(6, referenceObject); // closure #2
foo(2);

/*
num: 4
array: 1,2,3,4
obj.value: 10
*/

1 个答案:

答案 0 :(得分:3)

foo 等于iCantThinkOfAName,它等于iCantThinkOfAName(2, referenceObject),它返回包含{{的闭包内的内部函数doSomething 1}}(等于您传入的num),2这是您传入的objreferenceObject

当您致电array = [1, 2, 3];时,您直接呼叫内部foo(2)doSomething是您传递的i2会被添加到num这是你原来的2;因此,封闭内的num现在是4