Scope 未捕获关闭范围—;咖啡脚本
好吧,我不知道这个问题的标题怎么说Scope 未捕获关闭范围—;咖啡脚本,scope,coffeescript,Scope,Coffeescript,好吧,我不知道这个问题的标题怎么说 openDir = (path) -> socket.emit "get_metadata", path, (data) -> columnBox = $ "<div/>", class: "columnbox" for item in data.contents itemBox = $ "<div/>", class: "itembox" itemBox.click ->
openDir = (path) ->
socket.emit "get_metadata", path, (data) ->
columnBox = $ "<div/>", class: "columnbox"
for item in data.contents
itemBox = $ "<div/>", class: "itembox"
itemBox.click ->
columnBox_inner.children().removeClass "selected"
itemBox.addClass "selected" # <<<--- Over here
openDir item.path
columnBox.append itemBox
columnBox.appendTo "#columnscontainer"
进入
但是我想知道为什么lambda函数不捕获变量当前值。此循环:
for item in data.contents
itemBox = $ "<div/>", class: "itembox"
将itemBox
范围分别限定到循环的每个迭代
使用forEach的
data.contents.forEach (item) ->
而不是简单的循环,因为您有效地使用了一个函数作为循环体,该函数中的任何变量都将被限定为该函数的作用域。我知道作用域部分。但您提到的“单击处理程序保留对itemBox
的引用,但在调用单击处理程序之前不计算变量”是我不知道的。我假设对变量指向的对象的引用由click处理程序保留。谢谢这个问题也适用于openDir item.path
行中引用的item
变量,即使它是在openDir
的范围中定义的。
for item in data.contents
itemBox = $ "<div/>", class: "itembox"
itemBox = undefined
for item in data.contents
itemBox = $ "<div/>", class: "itembox"
for item in data.contents
do (item) ->
# As before...
data.contents.forEach (item) ->