Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to call function.apply without changing the context?
    primarykey
    data
    text
    <p>In some Javascript code (node.js specifically), I need to call a function with an unknown set of arguments without changing the context. For example:</p> <pre><code>function fn() { var args = Array.prototype.slice.call(arguments); otherFn.apply(this, args); } </code></pre> <p>The problem in the above is that when I call <code>apply</code>, I'm change the context by passing <code>this</code> as the first argument. I'd like to pass <code>args</code> to the function being called <strong>without</strong> changing the context of the function being called. I essentially want to do this:</p> <pre><code>function fn() { var args = Array.prototype.slice.call(arguments); otherFn.apply(&lt;otherFn's original context&gt;, args); } </code></pre> <p><strong>Edit:</strong> Adding more detail regarding my specific question. I am creating a Client class that contains a socket (socket.io) object among other info pertaining to a connection. I am exposing the socket's event listeners via the client object itself.</p> <pre><code>class Client constructor: (socket) -&gt; @socket = socket @avatar = socket.handshake.avatar @listeners = {} addListener: (name, handler) -&gt; @listeners[name] ||= {} @listeners[name][handler.clientListenerId] = wrapper = =&gt; # append client object as the first argument before passing to handler args = Array.prototype.slice.call(arguments) args.unshift(this) handler.apply(this, args) # &lt;---- HANDLER'S CONTEXT IS CHANGING HERE :( @socket.addListener(name, wrapper) removeListener: (name, handler) -&gt; try obj = @listeners[name] @socket.removeListener(obj[handler.clientListenerId]) delete obj[handler.clientListenerId] </code></pre> <p>Note that <code>clientListenerId</code> is a custom unique identifier property that is essentially the same as <a href="https://stackoverflow.com/a/7579956/107277">the answer found here</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload