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?
Webpack, Babel, UglifyJS, and TypeScript are the most popular alternatives and competitors to Closure Compiler.
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.
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.
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.
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.
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