Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between functionName() and functionName.call() in javascript

Tags:

javascript

Hopefully the title is self explanatory, what is the advantage of using the .call() method in Javascript compared with just writing functionName(); ?

like image 427
jonhobbs Avatar asked Feb 02 '26 23:02

jonhobbs


2 Answers

functionName.call() takes an object instance as its first parameter. It then runs functionName within the context of that object instance (ie "this" is the specified instance)

like image 68
David Arno Avatar answered Feb 05 '26 12:02

David Arno


If you don't pass anything into call(), it will be the same; the function will be run with the same scope that the call to call() is made:

function test() {
    alert(this);
}

test(); // alerts the window object
test.call(); // alerts the window object

But if you pass an object into call(), that object will be used as the scope:

test.call("hi"); // alerts "hi"
like image 40
Ates Goral Avatar answered Feb 05 '26 12:02

Ates Goral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!