'this' in function.call() behaves differently when this is not present

Viewed 100

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

3 Answers

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);

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

test.call(null, ...args);

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)
Related