简体   繁体   English

javascript - 在定义函数的同时调用函数的快捷方式

[英]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 . 不会。您的第二个示例将立即调用匿名函数并将其返回值分配给newfunc

adamse describes an approach which appears to work. adamse描述了一种似乎有效的方法。 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. 模式#1:单身人士。 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! 模式#2:自动执行匿名功能......因为太多原因而得心应手!

// 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: 我使用“NS”作为示例命名空间:

// 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: 您还可以使用.call或.apply而不是通常的括号来设置自执行函数的上下文,如下所示:

(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. 您将收到两个警报,第一个将显示“默认值”,第二个将显示“我不是默认值。您可以在jsBin中查看它。点击'预览'以使其运行。

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 还将呈现警报消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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