In closure tag wiki page, it reads "jQuery itself is one big closure."
But is promise a closure as well? Could you please explain why or why not? This is how I understand closure: assign a function to a variable and reuse it with different environments. Promise does that with $.ajax()
, but I could not find anywhere in stackoverflow where promise is introduced as a closure. Maybe because there are other features of promise like $.Deferred()
, resolve()
, and fail()
to expand its functionality beyond a simple function passing?
This is how I understand closure: assign a function to a variable and reuse it with different environments.
That's not a strictly accurate definition of a closure.
A closure is a function that has access to a referencing-environment. In Javascript, that means a function that is returned by another function and has access to the original functions scope. there are other SO questions that describe this very well
Closure's are general purpose structures that can be used in a variety of ways. One of their biggest benefits is that they protect private scope, which is why libraries like jQuery are often written as closures, so that they don't need to expose all their functions globally.
Promises are a different concept. They are a way of structuring asynchronous code to make it easier to follow the flow. A promise object in particular is an object that provides functions to chain operations in a clear and easy to read way. A promise might be implemented using closures, but it does not have to be. For instance here is an implementation that does not use closures:
https://gist.github.com/814052/690a6b41dc8445479676b347f1ed49f4fd0b1637
whereas jQuery's implementation uses at least one closure, but isn't really based on them
http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.Deferred
Promises and Closures aren't directly related concepts. Closure's are a programming technique that might be used in a Promise implementation. In the end it is neither impossible or necessary to implement it like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With