Javascript Closure not taking inputs consistently

流过昼夜 提交于 2021-02-11 14:49:18

问题


I have two javascript closures and I'm trying to understand why one will accept and input with a particular syntax and the other will reject.

function multiply(factor) {

  var ace = (function(number) {
      return number*factor;
  });

  return ace;

} 

var yup = multiply(4);
console.log(yup(5));

This outputs 20 to the console as it should.

The second Closure I have is

var k = 3;
var add = (function () {
  console.log(k);
  var counter = k;
  return function (j) {counter += 1; return counter*j}
})(k);

add();
console.log(add(5));

The output is 20 as it should be.

This issue I'm having that if I try to use the syntax of

(function() {

})(number);

In the first closure it does not work and outputs "number is not defined" And if I try to input into the second closure

(function (k) {
  var counter = k;
  return function (j) {counter += 1; return counter*j}
});

I get out

function (j) {counter += 1; return counter*j}

to the console.

My question is, what am I not understanding about closers the () at the end of them.


回答1:


The difference is whether you are creating the closure right away through an IIFE, or a function that makes the closure when called.

Your first snippet written in the second style would be

var yup = (function multiply(factor) {
  return function ace(number) {
    return number*factor;
  };
})(4); // the multiply(4) call is inlined into the statement with the definition
console.log(yup(5));

Your second snippet written in the first style would be

function makeAdd(k) {
  console.log(k);
  var counter = k;
  return function (j) {
    counter += 1;
    return counter*j;
  }
}
var add = makeAdd(3);
add();
console.log(add(5));


来源:https://stackoverflow.com/questions/55230521/javascript-closure-not-taking-inputs-consistently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!