In Javascript is there equivalent to .apply that doesn't change the value of this?

JussiR picture JussiR · Mar 9, 2011 · Viewed 9.4k times · Source

Seems easy enough, i want to call a function with array of arguments. Sure, i can say func.apply(this, ['some', 'arguments']); but that will change the value of this inside func. Any idea how to do this without changing it?

Answer

s4y picture s4y · Mar 9, 2011

You cannot, because of the way this works in JavaScript. Read on:

Going by the "Entering An Execution Context" section of the ECMAScript spec: when you call a function, the value of this is determined by what's to it's left (called the activation object) . Let's create a function called steve, and put him in an object:

function steve(){}
var obj = { method: steve };

…when we call steve as obj.method(), his this is obj, because obj was the activation object.

The tricky case is when nothing is to the left of a function call:

steve(); // Who am I ?!

There's nothing to the left of the function call — effectively, it's null — so the value of this is set to a default value of the global object (window in web browsers, global in Node.js, etc.).

So you are, in fact, setting a function's this every time you call it.

P.S. calling steve.apply(null, []) is equivalent to calling steve().