10
09/2014
javascript running at place
javascript 函数可直接 创建并就地执行(running at place)
Function Expression 可以 running at place
(gs = function(a) { if(!a)a=1; var b; return a; })()
注意:a,b 都是 局部变量。
After the execution, the global namespace is still clean. That’s a good practice.
执行后,全局名字空间还是干净的。
Function Declarations 也可以 running at place
(function $(a) { if(document.querySelector){ return a = document.querySelector(a); } else { //不支持 js 1.5 } })('body')
下面代码的错误何在?
var a = 5 (function() { alert(a) })()
TypeError: number is not a function
因为没有分号 ; 所以会被这样执行
var a = 5(function() {
alert(a)
})()
var b=function(k){return k;} a=b(1) 1 a 1 a=b function (k){return k;} a function (k){return k;} a(123) 123