https://github.com/mattdiamond/Recorderjs/blob/master/recorder.js中的代码
我不明白javascript的语法
(function(window){
// blah-blah
})(window)当我尝试下面的代码时,我可以在控制台中看到"hello world“。
(function(window){
console.log("hello world");
})(window)这是什么意思?有推荐信吗?
提前感谢
发布于 2014-03-28 06:37:32
这是什么意思?有推荐信吗?
它只是执行括号内的函数,就好像它被拆分为:
f = (function(window){
console.log("hello world");
})
f(window)发布于 2014-03-28 06:45:21
在任何JavaScript文件中,如果您编写了如下内容:
justFunction();
//function declaration
function justFunction()
{
alert("something");
}这将调用justFunction()并显示一个警报。定义这样的函数称为函数声明。
现在有另一种方法来定义函数
var anotherFunction = function() { alert ("something")}如果你写这样的东西
anotherFunction();
// Function Expression
var anotherFunction = function() { alert ("something"); }虽然anotherFunction是这里的一个函数,但这会给控制台带来一个错误。这就是所谓的函数表达式。
这背后的原因是函数声明在执行任何代码之前加载。而函数表达式仅在解释器到达该代码行时才加载。因此,如果您试图在函数表达式加载之前调用它,您将得到一个错误。
但是,如果您调用函数声明,它将始终工作。因为在加载所有声明之前,不能调用任何代码。因此,在定义函数表达式之后,必须始终调用它。
// Function Expression
var anotherFunction = function() { alert ("something"); }
anotherFunction();现在,可以通过在匿名函数后面添加括号立即调用函数表达式,如
var anotherFunction = function() { alert ("something"); }(); //paranthesis added这个代码片段和上面的代码片段做同样的事情(显示警报)。现在,anotherFunction变量与上面的不一样,因为它现在被赋值给匿名函数返回的值。现在,它没有返回任何内容,因此anotherFunction是未定义的。所以如果你写这样的东西
var anotherFunction = function() { alert ("something"); }();
anotherFunction(); //error这将导致错误,因为匿名函数不返回任何函数。如果它返回类似于
var anotherFunction =
function() { alert ("something"); return "some string"; }(); //returns stringanotherFunction现在是一个字符串变量。如果:
var anotherFunction = function() { alert ("something"); return function(){
alert("somethingElse")
}; }(); // returns function现在anotherFunction是一个函数,可以像anotherFunction().一样调用
可以将参数传递给此函数表达式,如下所示
var anotherFunction = function(p1,p2) { console.log(p1);
console.log(p2); }(param1,param2 ); //param1,param2 are parameters函数表达式和函数声明的主要区别之一是可以使用一组括号立即调用(调用)函数表达式,但函数声明不能。
现在,如果我们不想将函数表达式赋值给一个变量,那么我们必须将它写在括号内。
(function() { alert ("something");});要调用它,我们需要在末尾添加另一组括号,如下
(function() { alert ("something"); }());和前面一样,我们也可以将参数传递给它,例如:
( function(param){ console.log(param); }(param));这种类型的函数是##标题##called IIFE (立即调用函数表达式)。
IFFE只是一个匿名函数(没有附加名称),它被包装在一组圆括号内,并立即调用(调用)。
( function(){ }());推介
发布于 2014-03-28 06:49:05
以这个例子为例。
var message = 'hello world';
function Say(msg){
console.log(msg);
}
new Say(message);您可以通过不带括号的名称包装Say()并在其后面添加另一个括号并将消息传递给它,从而使其自调用匿名函数。
(function(msg){
console.log(msg);
})(message);https://stackoverflow.com/questions/22705818
复制相似问题