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()
.
Note that in ES6 you can also write:
func(...someArray)
Here this
becomes Window
inside func
, which is of no use. But if you write:
obj.func(...someArray)
this
in inside func
will be obj
.
This may be the feature i was looking for 5 years ago, but that was 5 years ago, so who remembers :)
The value of this
is no mystery when calling a function, depending on how it is called "normally" (without call
or apply
):
func(); // `this` is the global object, or undefined in ES5 strict modeobj.func(); // `this` is `obj`
So to avoid "changing" the value of this
, just pass in the correct value to apply
, depending on how you would call it "normally":
func.apply(undefined, []); // global object, or undefined in ES5 strict modeobj.func.apply(obj, []);