,這不是(未在鏈接的問題爲好)中提到的第一和第二語法之間的一個區別是,如果該函數返回一個函數對象使用「TheFunc」將是相當不同的結果
TheFunc = function(arg) {
return function(x) {
return arg+x;
}
}(5);
res = TheFunc(2); // res == 7
使其等於
TheFunc = function(5) {
return function(x) {
return 5+x;
}
}
res = TheFunc(2); // res == 7
因爲函數是匿名的。雖然
function TheFunc(arg) {
return function(x) {
return arg+x;
}
}
byFive = TheFunc(5);
res = byFive(2); // res == 7
會有相同的結果,但使功能工廠可重用。
的實際應用,將不會在這些例子中說清楚,但它可能是必不可少的,例如,在一個複雜的系統掛鉤周圍存在基於回調調用內置的情況下 - 比如使用插件系統:
// state object
function state(args) {
this.parse = function(data){
data = this.pre_parser(data);
// go on transforming data
return data;
}
}
state.prototype.pre_parser_factory = function(options){
...
}
var st = new state(args);
async_call(function(data, options){
st.pre_parser = st.pre_parser_factory(options);
res = st.parse(data);
})
第三會給你一個語法錯誤,除非你把一個函數的名字就可以了,([標籤聲明】(https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#label_Statement)沒有按不期望一個表達,但另一種說法)。可能重複的http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – CMS 2010-04-27 05:04:54
並且在這個問題的鏈接部分有很多類似的問題http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – YOU 2010-04-27 05:08:36
第三個可以是:xxx = {helloFunc:function(){...}} - 這是有效的。但當? – alexeypro 2010-04-27 05:09:07