João Sodré
João Sodré

Reputation: 11

How can I use ".call()" method in a javascript function and why does it have a "null" value?

So basically why do I have to use this kind of method in these kind of situations in particular?

function Example(callback) {  
    // What's the purpose of both 'call()' and 'null'?  
    callback.call(null, "Hello") 
}  

Exemple(function(callback) {  
    alert();
})  

I've figured it out this syntax in a open project code but I haven't found out why it works yet.

Upvotes: 1

Views: 35

Answers (2)

georg
georg

Reputation: 214959

This looks pointless at the first glance, however, there might be valid reasons for this syntax, for example:

  • the callback relies explicitly on this being null and not some global default

  • the callback is not necessarily a function, it can be a "function-alike" object that provides a .call method

  • callback.call(... is used consistently through the application, no matter if this is needed or not

Upvotes: 1

Mark
Mark

Reputation: 92440

You don't need to use call() in this situation. call() is used when you need to set the value of this in a function. If you aren't doing that, just call the function like you would any other function. For example:

function Example(callback) {  
    // call the function passed in
    callback("Hello") 
    // this also works, but there's no benefit here
    // because the callback doesn't care about `this`
    // callback.call(null, "Hello") 
}  

// pass a callback function to Example
Example(function(text) {  
   console.log(text);
}) 

You would use call in situations where the callback function needs a value for this. For example:

function Example(callback) { 
    let person = {name: "Mark"} 
    // set this in the callback to the person object 
    // and the execute it with the argument "Howdy"
    callback.call(person, "Howdy") 
}  

Example(function(greeting) {  
   // the callback function depends on having this.name defined
   console.log(greeting, this.name);
}) 

Upvotes: 1

Related Questions