How can I avoid using this snippet in closing Javascript?

I use this snippet in Javascript as 100 times a day to close a closing object:

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

Is there a way to avoid the Ta variable and still refer to the β€œexternal” (is the word correct?) object?

+6
source share
4 answers

a) You can continue to use this approach with more meaningful variable names. Using that is a general convention - this indicates that your variable is just a different "this" value, but for a different scope of functions.

b) You can use the function binding utility. Some JavaScript libraries come with one. Or you can just flip your own:

 function bind(fn, scope) { return function () { fn.apply(scope, arguments); }; } // for your example: Class.prototype.Method = function(arg) { var e = bind(function() { this.doSomething(arg); }, this); }; // Alternatively, extend the Function prototype (may raise some eyebrows): Function.prototype.bind = function (scope) { var fn = this; return function () { fn.apply(scope, arguments); }; }; // for your example: Class.prototype.Method = function(arg) { var e = function() { this.doSomething(arg); }.bind(this); }; 

Update: As @Pointy pointed out, bind is actually part of a new version of the JavaScript specification that modern browsers already use: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

+2
source

I do not know that I would defend this as excellent, but you could use ".bind ()":

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

This ensures that the this value inside the e function will always be the this value of the surrounding context. The .bind() function is available in new browsers or through polyfill, as well as on the MDC website.

I like to store these local variables, especially in complex functions that configure event handlers and the like; this helps clarify the relationships between the layers of code.

+3
source

I do not believe that there is. I do the same all the time.

0
source

I use a small home structure to easily use prototype inheritance, and in this structure I have the same code. I think there is no way to do without this.

Now the question is: why not do it? Do you think this is bad practice and why?

The piece of code that I use:

 function getCallback(obj, methodName) { var method = obj[methodName]; function callback() { if (obj[methodName] === callback) { return method.apply(obj, arguments); } return obj[methodName].apply(obj, arguments); } return callback; } 
0
source

Source: https://habr.com/ru/post/890496/


All Articles