Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing 'this' in Javascript closure

Tags:

javascript

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?

like image 819
Toji Avatar asked Jan 27 '11 05:01

Toji


People also ask

What is the closure in JavaScript can access?

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.

How do you use closures in JavaScript?

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.

What are the examples of closures in JavaScript?

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.

What kind of access closure variables have?

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.


1 Answers

This is the commonly accepted pattern with the exception that that is often used instead of self.

like image 91
aaronasterling Avatar answered Sep 25 '22 00:09

aaronasterling