简体   繁体   中英

javascript - shortcut for calling a function at the same time it is defined

to call a function at the same time it's defined, i had been using:

var newfunc = function() {
    alert('hi');
};
newfunc();

is the following the correct way of combining these 2:

var newfunc = function() {
    alert('hi');
}();

No. Your second example will immediately call the anonymous function and assign its return value to newfunc .

adamse describes an approach which appears to work. I'd still avoid the approach as the two step process is easier to read and thus will be easier to maintain.

var newfunc = function f() {
    alert("hi!");
    return f;
}();

Having a named function expressions allows the function to recursively call itself or, in this case, return itself. This function will always return itself, however, which might be an annoyance.

There could be a number of reasons you wish to do this. I'm not sure what yours are, but let me introduce a couple of favourite patterns:

Pattern #1: A singleton. The function is executed and then becomes a singleton object for use by other components of your code.

var singletonObject = new function() {

    // example private variables and functions
    var variable1 = {};
    var variable2 = {};
    var privateFunction = function() { 
    };

    // example public functions
    this.getData = function() { 
        return privateFunction(variable1, variable2);
    };

    // example initialisation code that will only run once
    variable1.isInitialised = true;
};

Pattern #2: Self-executing anonymous function ... handy for sooo many reasons!

// Declare an anonymous function body. 
// Wrap it in parenthesis to make it an "expression.
// Execute it by adding "();"
(function(){})();

And here's an example that also creates a namespace for your objects. I'm using "NS" as an example namespace:

// declare the anonymous function, this time passing in some parameters
(function($, NS) {

    // do whatever you like here

   // execute the function, passing in the required parameters. 
   // note that the "NS" namespace is created if it doesn't already exist
})(jQuery, (window.NS = window.NS || {}));

You can also set the context of a self-executing function by using .call or .apply instead of the usual parenthesis, like this:

(function($){
    // 'this' now refers to the window.NS object

}).call(window.NS = window.NS || {}, jQuery);

or

(function($){
    // 'this' now refers to the window.NS object

}).apply(window.NS = window.NS || {}, [jQuery]);

If I understand your question correctly, give this a try:

(f = function (msg) {
  msg =  msg ? msg : 'default value';
  alert(msg); }
)();


f('I\'m not the default value!');

You'll get two alerts, the first one will say "default value" and the second will say "I'm not the default value. You can see it in action at jsBin . Click 'preview' to make it run.

you could do like this:

o = {};
o.newfunc = ( function() {

function f() {
    alert('hi');
}
f();
return {
    f : f
};
}
)();

then calling the function like:

o.newfunc.f();

will also render an alert message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM