How is a closure different from a callback?

2019-01-16 11:31发布

I asked a question about callbacks and arrived at another question (see comment). How is a closure different from a callback?

9条回答
女痞
2楼-- · 2019-01-16 12:27

What is a callback function?

A callback function is a function which is:

  • passed as an argument to another function
  • is invoked(लागू) after some kind of event
  • once its parent function completes, the function passed as an argument is then called

in Plain English we say A callback is any function that is called by another function, which takes the first function as a parameter or function passed as an argument

  • Note : invoked : The code inside a function is executed when the function is invoked. or we say like this It is common to use the term "call a function" instead of "invoke a function".

It is also common to say "call upon a function", "start a function", or "execute a function".

 function getUserInput(firstName, lastName, age, callback2,callback1) {
    var fullName = firstName + " " + lastName;

    // Make sure the callback is a function
    if (typeof callback2 === "function") {
    // Execute the callback function and pass the parameters to it
    callback2(fullName, age);
    }
	
    if (typeof callback1 === "function") {     
    callback1(lastName);
    }
}

function callbackforlastname1(lname){
 console.log("---");
}
 
function genericPoemMaker(name, aged) {
    console.log(name + " is finer than fine wine.");
     console.log("A " + aged + " of unfortunl smile");
}

getUserInput("Avinash", "Maurya", "26", genericPoemMaker,callbackforlastname1); 
ऐसे कॉल करते है

查看更多
Explosion°爆炸
3楼-- · 2019-01-16 12:30

In simple words: a callback using context variables is a closure.

查看更多
▲ chillily
4楼-- · 2019-01-16 12:32

closure :

  • A function keyword inside another function, you are creating a closure

  • Or A function return to an other function we can say closure

Note Plain English : A little bit difference function passing as argument in another function is callback or if define in another function is closure

var length = 101;
function fn2() {
	console.log("fffxxx: "+this.length);
}
 
var obj = {
  length: 5,
  method3: function(fn) {
    fn();
    arguments[0]();
  }
};
 
obj.method3(fn2, 1);
   
**Outputहोगा

fffxxx:101
fffxxx:2**
查看更多
登录 后发表回答