Javascript 立即调用函数模式 [英] Javascript immediately invoked function patterns

查看:21
本文介绍了Javascript 立即调用函数模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么称呼这些模式?它们之间有什么区别?你什么时候用?还有其他类似的模式吗?

What do you call these patterns? What is the difference between them? When would you use each? Are there any other similar patterns?

(function() {
    console.log(this);  // window
})();

(function x() {
    console.log(this);  // window
})();

var y = (function() {
    console.log(this);  // window
})();

var z = function() {
    console.log(this);  // window
}();

通过命名最后两种情况下的函数,我发现了两种看似多余的方法来做到这一点......

I just found two more seemingly redundant ways to do this by naming the functions in the last two cases...

var a = (function foo() {
    console.log(this);  // window
})();

var b = function bar() {
    console.log(this);
}();

下面是@GraceShao 提供的另一种模式,它使函数可以在函数范围之外访问.

Here is another pattern provided below by @GraceShao which makes the function accessible outside the function scope.

(x = function () {
    console.log(this);  // window
    console.log(x);     // function x() {}
})();
console.log(x);         // function x() {}

// I played with this as well 
// by naming the inside function 
// and got the following:

(foo = function bar() {
    console.log(this);  // window
    console.log(foo);   // function bar() {}
    console.log(bar);   // function bar() {}
})();
console.log(foo);       // function bar() {}
console.log(bar);       // undefined

推荐答案

这里又是你的函数,并附有一些注释,描述了它们何时/为什么有用:

Here are your functions again with some comments describing when/why they might be useful:

(function() {
    // Create a new scope to avoid exposing 
    // variables that don't need to be
    // This function is executed once immediately
})();

(function fact(i) {
    // This named immediately invoked function 
    // is a nice way to start off recursion
    return i <= 1 ? 1 : i*fact(i - 1);
})(10);

var y = (function() {
    // Same as the first one, but the return value 
    // of this function is assigned to y
    return "y's value";
})();

var z = function() {
    /* This is the exact same thing as above 
     (except it is assigned to z instead of y, of course).
     The parenthesis in the above example don't do anything
     since this is already an expression
    */
}();

这篇关于Javascript 立即调用函数模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆