例如:
(function($) {
document.getElementById("foo").innerHTML = 'bar';
})();
Run Code Online (Sandbox Code Playgroud)
我知道我们想要创建自己的范围来防止变量冲突,但为什么javascript需要有()()?
这使它成为一个自我调用的匿名函数.
(function() {
/* function body */
}) /* <-- end of function definition */ (); // <-- invoke that function immediately
Run Code Online (Sandbox Code Playgroud)
它没有()(),它有(function(){})().
函数语法是function(){}函数调用操作符().包装函数的括号在技术上并不特殊,您可以用以下代码替换它们!:
!function(){}()
Run Code Online (Sandbox Code Playgroud)
这样做是行不通的:
function(){}()
Run Code Online (Sandbox Code Playgroud)
因为这在语句上下文中,function启动函数声明而不是表达式.然后语法失败,因为函数声明必须具有名称.
如果我们有!function(){}(或(function(){}),那么它不能是一个语句,因为!(或()已经期望一个表达式,所以它将被视为一个表达式.
所以你可以毫不费力地做到这一点:
var a = function() {
return false;
}();
Run Code Online (Sandbox Code Playgroud)
因为var a =已经期待一个表达式,function所以不可能是函数声明的开始.
石蕊测试你的功能是否会被视为表达或声明的一种简单方法就是问问自己,我可以var x在这里使用吗?
例如:
var x; //all is fine, so if I said function here, it would be a start of a function declaration
(var x) //Gives an error, so replacing var x with a function would be a function expression
var myVar = var x; //Gives an error, so replacing var x with a function would be a function expression
Run Code Online (Sandbox Code Playgroud)
等等
| 归档时间: |
|
| 查看次数: |
965 次 |
| 最近记录: |