Quick Overview
var f1 = function(){ var a = 999; nAdd = function(){n+=1} //没有var,nAdd是全局变量 f2 = function(){ alert(a) } return f2; } var result = f1(); result(); //999 nAdd(); //相当于一个setter,可以在函数外部操作函数内部变量的值 result(); //1000,f2()被执行了2次
Function within a function
You can read variables inside the function
Always keep the variables of the parent function in memory
Note: If you want to keep the variable values of the parent function unchanged, you need to use the parent function as an object
//父函数作对象 var name = 'The Window'; var object = { name : 'The Object', getName : function(){ return function(){ return this.name } } } alert(object.getName()()) //The Window
var _name = 'The Window'; var object = { _name : 'The Object', //_name 下划线表示私有变量 getName : function(){ var that = this; return function(){ return that._name; } } } alert(object.getName()()) //The Object
that=this / _this=this
Related recommendations:
Detailed introduction to JavaScript closures
Simple application of JavaScript closure examples
javascriptWhat is the closure? How to use javascript closure?
The above is the detailed content of Detailed explanation of javascript closure var that=this. For more information, please follow other related articles on the PHP Chinese website!