Problem with 'this' in function.call() in JavaScript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 97

Problem with 'this' in function.call() in JavaScript

Why the function.call() behaves differently with and without 'this', in JavaScript?
The result with 'this' in test.call() is same when 'this' is replaced by 'undefined'.

Code: Select all

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

let args = [1,2]
test.call(this, ...args); // Output: 3
test.call(undefined, ...args); // Output: 3

But without 'this' in test.call(), the result is NaN.

Code: Select all

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

let args = [1,2]
test.call(...args); // Output: NaN

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

Code: Select all

test.call(null, ...args);
In your code, 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.

Code: Select all

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 that string.

Code: Select all

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

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

Similar Topics