gpt4 book ai didi

Javascript 立即调用函数模式

转载 作者:可可西里 更新时间:2023-11-01 01:55:29 24 4
gpt4 key购买 nike

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

(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
}();

编辑:我刚刚发现了另外两种看似多余的方法,通过在最后两种情况下命名函数...

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

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

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

(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

最佳答案

这里再次是您的函数,并附有一些说明它们何时/为何有用的注释:

(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 立即调用函数模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com