1.什么是閉包
大多數(shù)書(shū)本中對(duì)閉包的定義是:“閉包是指有權(quán)訪問(wèn)另一個(gè)函數(shù)作用域中的變量的函數(shù)。”。這個(gè)概念過(guò)于抽象了,對(duì)初學(xué)者而言沒(méi)啥幫助。好在《Javascript忍者秘籍》5.1中給了一個(gè)例子來(lái)進(jìn)一步的解釋了什么是閉包:
var outerValue= 'ninja'; var later; function outerFunction() { var innerValue = "samurai"; function innerFunction(paramValue) { assert(outerValue == "ninja", "I can see the outerValue."); assert(innerValue == "samurai", "I can see the innerValue."); assert(paramValue == "wakizashi", "I can see the paramValue."); assert(tooLater == "ronin", "Inner can see the tooLater.&quo