В этом примере в Википедии (http://en.wikipedia.org/wiki/Closure_(computer_programming)) он утверждает, что при вызове переменной closure1
с closure1(3)
будет возвращен 4
. Может кто-то пройти через пример - я не понимаю.Закрытие - уточнение переменной и функции
function startAt(x)
function incrementBy(y)
return x + y
return incrementBy
variable closure1 = startAt(1)
variable closure2 = startAt(5)
Invoking the variable closure1 (which is of function type) with closure1(3) will return 4, while invoking closure2(3) will return 8. While closure1 and closure2 are both references to the function incrementBy, the associated environment will bind the identifier x to two distinct variables in the two invocations, leading to different results.
Если это помогает, вот мое настоящее понимание. variable closure1 = startAt(1)
задает переменную closure1
функции startAt()
, которая по умолчанию инициализируется значением 1
. Однако вызов closure1(3)
устанавливает это значение по умолчанию 3
. То, что я тогда не понимаю, это то, откуда y
.
variable closure1 = startAt(1)
Связанные: [Как работает закрытие JavaScript?] (Http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – apsillers
Закрытие - это только классы бедных классов. Занятия - это просто плохие закрытия. – leppie