Lorthas
Lorthas

Reputation: 376

Is it correct to use .call() to call a function immediately?

-Is it a proper way to use .call() to call a function instantly after it's declaration instead of using the syntax with parens like: Instead of using:

(function([params]){ 
    //Code goes here 
})(/*params*/);

Can we do this?:

(function(/*possible params*/){
    //Code goes here
}).call(/*scope, [params]*/);

I read in a blog or a page that using .call() can be used to invoke functions anonymously so I assume it is correct to do it. But I'm not sure what way of the 2 is better. I see it could be easier to use the first method.

Also, could I use this instantly invoking functions to, inside a literal object or a function constructor, create a variable inside that object which value is calculated doing some kind of algorithms inside an instantly self esecuted function when creating the object? I.E: the example is very stupidi example but... Sorry for the stupid example, I could not think of something better:

function Person(name, sex){
    this.name = name;
    this.sex = sex;
    this.description = (function(){
        let desc = "";
        let gender = "";
        if (sex == "male"){
            gender = "male";
        }
        else if (sex == "female"){
            gender = "woman";
        }
        desc += "I am a "+gender+" and my name is "+name;
        return desc;
    })(name, sex);
}

var p1 = new Person("Alice", "female");
alert(p1.description);

I tested it and it works, so I assume more complex things could be done and having variables private. Am I right? I would be thankful if you could resolve my doubts about this.

Upvotes: 0

Views: 58

Answers (1)

Naftali
Naftali

Reputation: 146310

There is no need to use .call or .apply on an IIFE function if there is no use of the this context within it as that is what call does for you.

The only reason I can see the need for it is maybe in a callback function where you need to bind the context in order to use this appropriately in the callback.

Upvotes: 1

Related Questions