Akash RP
Akash RP

Reputation: 61

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

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

Upvotes: 2

Views: 106

Answers (3)

Jack Yu
Jack Yu

Reputation: 2425

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

Upvotes: 2

York Chen
York Chen

Reputation: 742

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

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

Upvotes: 1

andersryanc
andersryanc

Reputation: 969

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)

Upvotes: 0

Related Questions