Last active
October 27, 2017 01:58
-
-
Save ThaddeusJiang/96a2baee99bdf4189775ae36fa6bcdf9 to your computer and use it in GitHub Desktop.
解释 JavaScript 闭包(Closure)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 😎 JS闭包: 定义在函数内的子函数,子函数作为函数返回值返回。 | |
// 效果:在函数外面通过子函数,可以访问函数的内部变量。 | |
// 运行效果 http://runjs.cn/detail/mvhnvgsq | |
function test1() { | |
var name = "The Window"; | |
var object = { | |
name: "My Object", | |
getNameFunc: function () { | |
return function () { | |
return this.name; // this 绑定到函数定义所在位置,即 getNameFunc。 | |
}; | |
}, | |
}; | |
alert(object.getNameFunc()()); | |
} | |
function test2() { | |
var name = "The Window"; | |
var object = { | |
name: "My Object", | |
getNameFunc: function () { | |
var that = this; // this 绑定到函数定义所在位置,即 object。 | |
return function () { | |
return that.name; | |
}; | |
} | |
}; | |
alert(object.getNameFunc()()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
要理解JS闭包,就必须理解变量作用域和this绑定。