匿名函数
(function(){
console.info("111111111");
})();
var my = (function(){
return "11111111";
})();
函数里放匿名函数叫闭包
function my(){
return function(){
return "张三";
}
}
console.info(my()());
闭包的优点,避免使用全局变量,提供访问局部变量
//把局部变量保存起来
function box(){
var age = 100;
return function(){
age++;
return age;
}
}
var b = box();
b();
b();
b();
function box1 (){
var arr = [];
for(var i=0;i<5;i++){
arr[i] = (function (num){
return num;
})(i)
}
return arr;
}
var my = function(){
return "11111111";
}();
闭包在全局是指向window,
var name ="全局";
var user ={
name:"张三",
getUser:function(){
var that = this;
return function(){
return that.name;//返回user对象的属性,而不是全局
}
}
}
块级作用域,(function(){
})();
function box(){ var arr = []; for (var i=0;i<5;i++) { arr[i] = (function(num){
//有时arr[i] 需要经过函数复杂计算,闭包的用处
return num; })(i); }
return arr; }
闭包this指向window
var name = "window";
var box = {
name:"box",
getName: function(){
//这里的作用域指向box
var that = this;
return function(){
//这里的作用域指向window
return that.name;
}
}
} alert(box.getName()());
var name1 = "1212";
(function(){
var name1 = "张三"
alert(this.name1);//指向window })();
//块级作用域,变成私有作用域
function Box(){
var name = "张三";//私有变量外部无法访问
function eat(){//私有方法外部无法访问
return "吃饭";
}
this.run = function(){//公有方法共外部调用
return name +eat();
}
}