Best practice for passing a callback function context

I have an object that has several methods, and I want to bind one of them as an event handler, but it uses other methods from the same object. What is the best practice for maintaining context in callback functions? As I see from the jQuery UI kernel, the $ .proxy method is usually used for this purpose, to be honest, I donโ€™t like this approach, itโ€™s not very clear.

Do you have any suggestions? Thanks in advance!

var obj = { someMethod: function(){...}, callback : function(){ ... this.someMethod(); // or this.someMethod.call(...) ... }, }; // wrong $.bind(elm, obj.callback); // using $.proxy $.bind(elm, $.proxy(obj.callback, obj)); 
+4
source share
1 answer

Your options are basically:

  • $.proxy (as you indicated)
  • JavaScript 1.8 Function.bind
  • _.bind implementation of Function.bind (e.g. _.bind )
  • Built-in anonymous function: $.bind(elm, function() { obj.callback.apply(obj, arguments })

None of them are definitely better or definitely worse than others (with the possible exception of the built-in anonymous functions, which are pretty detailed, and Function.bind and friends are a bit more general than $.proxy ). It is more important to choose one and be consistent.

+4
source

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


All Articles