闭包
闭包:
应用两种情况
1、函数作为返回值
2、函数作为参数传递
1、
function fn1(){
var max = 10;
return function bar(x){
if(x > max){
console.log(x)
}
}
}
var f1 = fn1();
f1(15);
2、
var max = 10,
fn2 = function (x) {
if(x > max){
console.log(x) //15
}
};
(function (f) {
var max = 100;
f(15)
})(fn2)
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
console.log(object.getNameFunc()());//The Window
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
console.log(object.getNameFunc()());//My Object