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

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().

Leave a Comment