2

I am learning javascript Why the function.call() behaves differently with this and without this.

The program with this in test.call() and result is same when this is replaced by undefined

function test(a,b){
    console.log(a+b);
}

let args = [1,2]
test.call(this,...args);

// Output: 3 

The program without this in test.call()

function test(a,b){
    console.log(a+b);
}

let args = [1,2]
test.call(...args);

// Output: NaN
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Akash RP
  • 61
  • 5
  • I think this link will help you to understand in more detail.. https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Parth Raval Nov 10 '20 at 06:09
  • .call needs a reference as first argument – Biswa Soren Nov 10 '20 at 06:09
  • 1
    "*and result is same when this is replaced by `undefined`*" but `test.call(...args);` is **not** replacing `this` with `undefined`. That invocation is equivalent to `test.call(1, 2);` so, `this = 1`, `a = 2`, and `b = undefined`. – VLAZ Nov 10 '20 at 06:09
  • the `this` parameter is not optional, if you want it to be `undefined` then call `call` like so: `test.call(undefined, ...args)`, otherwise `args[0]` (in this case `1`) will be used as `this` – ibrahim mahrir Nov 10 '20 at 06:11
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Durga Nov 10 '20 at 06:14
  • 1
    @Durga this is not a duplicate. The other SO question may help clarify a little bit but it's in no way a duplicate – ibrahim mahrir Nov 10 '20 at 06:15

3 Answers3

2

In this case, you pass args into the this in test function not into (a, b).
You can add console.log(this) to checkout the different between two cases.

function test(a,b){
    console.log(this) // number 1
    console.log(a) // number 2
    console.log(b) // undefined
    console.log(a+b) // 2 + undefined will be NaN
}

let args = [1,2]
test.call(...args);

So, that means the first argument will be this.
If you pass the string in first argument, your this will be "hihihi"

function test(a,b){
    console.log(this) // "hihihi"
    console.log(a) // number 1
    console.log(b) // number 2
}

let args = [1,2]
test.call("hihihi", ...args);
Jack Yu
  • 2,190
  • 1
  • 8
  • 14
1

call function require the first parameter as 'this' object, if you do not need it, just pass null.

test.call(null, ...args);
York Chen
  • 744
  • 4
  • 9
0

The correct syntax is to use .call() with this as the first argument. You can read more about Function.prototype.call here

func.call(this, arg1, arg2, ...argN)

or you can omit it by passing null:

func.call(null, arg1, arg2, ...argN)
andersryanc
  • 939
  • 7
  • 19