Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 669
JussiR Avatar asked Mar 09 '11 14:03

JussiR


People also ask

What is the value of this in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

What does let stand for in JavaScript?

Description. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Can you use this in a function JavaScript?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword.


1 Answers

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

like image 101
s4y Avatar answered Sep 18 '22 21:09

s4y