【发布时间】:2013-05-03 17:50:00
【问题描述】:
首先,据我了解,某些语法 javascript 和 actionscript 在函数方面的操作方式非常相似。在这两种语言中,我都需要将 局部变量 添加到某种事件侦听器中。例如在动作脚本中:
public class Foo {
public function handleBar():void {
this.bla(); this.blabla();
}
public function createButton():void {
SomeSortOfButton button = new SomeSortOfButton();
//HERE COMES THE AWKWARD PART:
button.addEventListener(MouseEvent.CLICK,
(function (foo:Foo) {
return function (event:MouseEvent):void {
//I want to do stuff with foo, hence the function that returns a function.
foo.handleBar();
};
})(this)
);
}
}
在 javascript (+jquery) 中,我时不时会有这样的东西:
var foo = ......;
$("#button").click(
(function(bar) {
return function(event) {
//do stuff with bar (which is defined as foo in the first line)
};
)(foo)
);
我喜欢它的工作方式,但就语法而言,这是一个完整的不行恕我直言。有没有其他选择?我在 actionscript 中尝试的是在处理程序中使用默认参数:
public class Foo {
public function handleBar():void {
this.bla(); this.blabla();
}
public function createButton():void {
SomeSortOfButton button = new SomeSortOfButton();
//HERE COMES THE ALTERNATIVE:
button.addEventListener(MouseEvent.CLICK,
function (event:MouseEvent, foo:Foo = this):void {
//I want to do stuff with foo, hence the function that returns a function.
foo.handleBar();
}
);
}
}
但这是不允许的,因为 foo:Foo = this 中的 this 无法在编译时解析。很公平,但我仍然想知道,在 javascript 和 actionscript 中是否有上述构造的语法糖?我非常喜欢使用单个函数,而不是返回函数的函数。
我希望得到的答案是:“(据我所知,)没有其他方法可以传递局部变量”或“是的,你可以这样做: ...."。
当然,任何评论都非常感谢!
【问题讨论】:
-
很难说出你想要达到的目标。在您的 JavaScript 示例中,您正在跳过箍以避免让您的事件处理程序使用
foo。为什么?因为你以后要换foo? -
如果您在事件处理程序中引用 foo,即在内部函数的 {} 内,这仅在 foo 是全局变量时才有效。此外, foo 也可能像你说的那样改变。
-
@Herbert:不,
foo不必是全局变量。它只需要在定义函数的范围内。全局变量只是该一般原则的一个特例。更多:Closures are not complicated
标签: javascript function actionscript local-variables