This is more of a sanity check than anything else. I've found that when working with closures in Javascript I often use the following pattern to access the enclosing class from within the function:
MyClass.prototype.delayed_foo = function() {
var self = this;
setTimeout(function() {
self.foo(); // Be nice if I could use 'this' here
}, 1000);
};
Obviously this works just fine, and it's not even a big hassle to work with. There's just this little itch in the back of my brain that says 'You're making this too complicated, dummy!' Is this the commonly accepted pattern?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function. The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
Let's have a look at another example. In the above program, the calculate() function takes a single argument x and returns the function definition of the multiply() function. The multiply() function takes a single argument y and returns x * y . Both multiply3 and multiply4 are closures.
A closure is an inner function that has access to the outer (enclosing) function's variables — scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.
This is the commonly accepted pattern with the exception that that
is often used instead of self
.
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