Javascript function call with an unknown number of arguments with the original context

I am currently using Function.apply to call a function with a dynamic number of arguments, but I do not have access to the original context, and I do not want to set the context myself. I would like to be able to call a function with a variable number of arguments, preserving the original context.

Maybe some code should show you what I'm trying to do:

function MulticastDelegate() { var handlers = []; this.event = { subscribe: function(handler) { if (typeof(handler) === 'function') { handlers.push(handler); } }, unsubscribe: function(handler) { if (typeof(handler) === 'function') { handlers.splice(handlers.indexOf(handler),1); } } } this.execute = function() { var args = Array.prototype.slice.call(arguments); for (var handler in handlers) { // call this with the original context of the handler handlers[handler].apply(null, args); } } } 

Essentially, I want the apply behavior β€” the ability to pass an array of arguments β€” without the call behavior β€” to change the context in which the function is executed.

+6
source share
2 answers

There is no such thing as a "source context" function. You would need to do something like this:

 subscribe: function(handler, context) { if (typeof(handler) === 'function') { handlers.push([handler, context]); } }, 

And then of course

 handlers[handler][0].apply(handlers[handler][1], args); 

Alternatively (this is what I would do), leave it to the caller to make sure the handler has the correct context. For example, instead of delegate.subscribe(this.foo) , let's say

 var self = this delegate.subscribe(function () { self.foo() }) 

Or using Function.prototype.bind ,

 delegate.subscribe(this.foo.bind(this)) 
+5
source

Maybe .bind will solve the matter? http://documentcloud.github.com/underscore/#bind
In this case, you get the function "attached" to the original context

0
source

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


All Articles