用return function /object 提高效率
首先来对比两段代码:
代码(1)
var aa = (function(){
var b = 1;
alert(b);
var c = b * 2;
return {
oo:c,
ob:2
}
})()
alert(aa.oo);
alert(aa.oo)
结果:加载时先弹出1,运行两个alert(aa.oo)时再弹出两个2
代码(2)
var aaa = {
oo:function(){
var b = 1;
alert(b)
var c = b * 2;
return c;
},
ob:2
}
alert(aaa.oo())
alert(aaa.oo())
结果:加载时不运行,调用时先后弹出两个1和两个2
从上面的结果可以看出,第一种方法在函数多次调用时可以减少一些不必要的语句执行(这个看具体情况),从而提高效率,而第二种调用一次则函数体所有语句都会执行一次,相对效率会差一点。
这种方法可以应用在一些只需要运行一次的地方(比如取得某个元素的长度)等,以减少一些不需要的运算。
看来以前的理解太肤浅,总以为只是一些花哨的写法而已,原来藏着这么多学问,以后真要好好学习。
另一篇文章:
As far as JavaScript is concerned, a function is just another type of object and so we can return functions from our functions if we wish. Where we have a function that returns a function we can have the code in the main function returning different functions depending on what parameters are passed into it and so when the returned function comes to be run it can actually do different things depending on which function is returned.
The function to be returned can either be defined within the return statement as shown in this example or it can be assigned to a variable prior to the return statement and then that variable just needs to be returned to return the function. In this example we return one of two functions to assign to the stopDef variable depending on whether the JavaScript or JScript way of preventing the default action from running is the one supported by the browser. We can then simply call that stopDef function to run whichever function our create function returned.
createStopDef = function(e) { if (e && e.preventDefault) return function(e) {e.preventDefault();}; else if (window.event && window.event.returnValue) return function() window.event.ReturnValue = false;}; }; stopDef = createStopDef(e); stopDef(e);
stackoverflow:http://stackoverflow.com/questions/7629891/functions-that-return-a-function-javascript
In your example, you are also defining functions within a function. Such as:
function d(){
function e(){
alert('E');
}
return e;
}
d()();
//alerts 'E'
The function is still callable. It still exists. This is used in JavaScript all the time. Functions can be passed around just like other values. Consider the following:
function counter(){
var count =0;
return function(){
alert(count++);
}
}
var count = counter();
count();
count();
count();
The function count can keep the variables that were defined outside of it. This is called a closure. It's also used a lot in JavaScript.