<script> var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ console.log("11111"); console.log(this); //this == object //调用该匿名函数的是对象 return function(){ console.log("22222"); console.log(this); //this == window //匿名函数下的匿名函数 return this.name; }; } }; alert(object.getNameFunc()()); //-- var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ var that = this; return function(){ console.log("33333"); console.log(this); //this==window console.log("44444"); console.log(that); //that==object return that.name; }; } }; alert(object.getNameFunc()()); </script>
function makeFunc() { var name = "Mozilla"; function displayName() { alert(name); } return displayName; //返回一个函数 } var myFunc = makeFunc(); //把函数返回值赋值给myFunc console.log(myFunc); //输出函数内容 myFunc();//调用函数
function makeAdder(x) { return function (y) { //返回一个函数 return x + y; //返回值 }; } var add4 = makeAdder(); //无传参函数返回值 console.log("//无传参函数返回值"); console.log(add4);//输出函数体 console.log(add4(2)); //NaN Number.NaN 是一个特殊值,说明某些算术运算(如求负数的平方根)的结果不是数字 var add5 = makeAdder(5); //把函数返回值赋值给add5, console.log("//有参函数返回值"); console.log(add5);//输出函数体 console.log(add5(2));//7
var Counter1 = (function () { })(); console.log("输出立即调用函数返回值Counter1"); console.log(Counter1); //undefined var Counter2 = (function () { var privateCounter = 0; })(); console.log("输出立即调用函数返回值Counter2"); console.log(Counter2); //undefined var Counter3 = (function () { var privateCounter = 0; function changeBy(val) { privateCounter += val; } } )(); console.log("输出立即调用函数返回值Counter3"); console.log(Counter3); //undefined //-- var Counter4 = (function () { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { value: function () { return privateCounter; } } } )(); console.log("输出立即调用函数返回值Counter4"); console.log(Counter4); //{value: ƒ} //类型object
var Counter = (function () { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function () { changeBy(1); }, decrement: function () { changeBy(-1); }, value: function () { return privateCounter; } } })(); console.log(Counter.value()); /* logs 0 */ //返回0 Counter.increment(); //执行0+1 Counter.increment(); //执行1+1 console.log(Counter.value()); /* logs 2 */ //输出2 Counter.decrement(); //执行2+(-1) console.log(Counter.value()); /* logs 1 */ //输出1
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures