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?
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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With