Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid using this snippet in Javascript closures?

I use this snippet in Javascript like 100 times a day to have a closure on the enclosing object:

Class.prototype.Method = function(arg){
    var Ta = this;
    var e = function(){
        Ta.doSomething(arg);
    };
};

it there a way to avoid the Ta variable and still refere to the "outer" (is this word correct?) object?

like image 653
gotch4 Avatar asked Jun 14 '11 12:06

gotch4


People also ask

What could be the alternative to closure?

Webpack, Babel, UglifyJS, and TypeScript are the most popular alternatives and competitors to Closure Compiler.

How do I avoid using JavaScript?

It's possible to avoid using this in the constructor, by using Object. create to create the prototype chain, then declaring your properties directly on the resulting object. This removes the need for this in your Shape function, meaning that we no longer need to call it with new either.

How will you explain closures in JavaScript when are they used?

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.

What are the disadvantages of using closures?

Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.


1 Answers

I don't know that I'd advocate this as superior, but you could use ".bind()":

var e = function() {
  this.doSomething(arg);
}.bind(this);

That ensures that the this value inside function "e" will always be the this value of the surrounding context. The .bind() function is available in newer browsers, or via a polyfill like the one on the MDC site.

I rather like keeping those local variables around, especially in complicated functions that set up event handlers and stuff like that; it helps clarify the relationships between layers of code.

like image 100
Pointy Avatar answered Sep 20 '22 05:09

Pointy