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:107
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
Posts:805
The
call() function require the first parameter as 'this' object, if you do not need it, just pass
null.
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
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax
First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
Last post
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =...
- Display message to every minute in Javascript
JavaScript - jQuery - Ajax
First post
Hello,
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
Last post
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...