2. 事件处理程序
对事件处理程序使用函数式编程也许是最直观的函数作为值得应用了。既然这样我们马上就演示一个例子。
简单的例子:;ie
现在有一个Button类,带一个自定义的onclick行为。function Button(clickFunction) {
this.button = document.createElement("button");
this.button.appendChild(document.createTextNode("Press me!"));
this.button.onclick = clickFunction;
}
var bt = new Button(function() { alert("42"); });
练习: 为什么我们要把alert包裹在一个匿名函数中?
高级例子:
现在我们想改进我们的Button类。每一个按钮都被分配了一个值当按钮被点击时显示该值。首先我们调整我们的类:
function Button(value) {
this.value = value;
this.button = document.createElement("button");
this.button.appendChild(document.createTextNode("test"));
}
下面你也许要尝试写下面的代码:
this.button.onclick = function() { alert(this.value); };
如果你执行它你就会发现提示框中间是空的。为什么会这样呢?其实原因在于JavaScript的可见性规则。当onclick函数被执行时this指向的是按钮的DOM节点而非自定义的按钮对象。
我们如何解决这个问题? 使用函数式编程:
this.button.onclick = (function(v) {
return function() { alert(v); };
}) (this.value);
这种情况下执行该匿名函数会将v绑定到this.value上。
沙箱
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]










