学习闭包,这种解释是否正确?

时间:2017-09-23 02:51:54

标签: javascript closures

我写了一个函数,它接受一个起始整数,然后不断添加它:

function sumFunc(base_integer) { 
  function increment(value_to_add) {
    base_integer += value_to_add
    console.log(base_integer)
  }
  return increment;
}

var summing = sumFunc(1) // 1 is the base
summing(4) // returns 1 + 4 = 5
summing(5) // returns 5 + 5 = 10

这是我的学习者试图解释幕后发生的事情:

var summing = sumFunc(1)

// this creates a variable summing which refers to the sumFunc
// with base_integer local variable set as 1, so it's kind of like this:
// summing = { 
//     var base_integer = 1
//     function increment(value_to_add) {
//       base_integer += value_to_add
//       console.log(base_integer)
//     }
//     return increment;
//   }
// per last line, summing is equal to the return value of the increment function

summing(4)

// because summing is equal to the return value of the inner increment function
// calling summing() executes the inner increment fn to get its return value
// we pass the parameter 4, which is passed to increment, since that's the fn that summing is calling
// because base_integer was earlier set as 1, we now have 1+4 as the logged value

summing(5)

// repeats the above, and since base_integer was previously redefined as 5, now that's the value that the new 5 is added to

这是对的吗?

0 个答案:

没有答案