我正在阅读 javascript:Douglas Crockford 的精彩部分。我很难理解一个特定的例子和作者提供的解释。
示例 1:(第 38 页)
var quo=function (status) {
return {
get_status:function() {
return status;
}
};
};
var myQuo=quo("amazed");
document.writeln(myQuo.get_status());
书中的解释(我不明白。请解释这部分):
这个quo函数被设计成不带new前缀使用,所以名字不大写。当我们调用quo时,它返回一个包含get_status方法的新对象。对该对象的引用存储在 myQuo 中。即使 quo 已经返回,get_status 方法仍然有权访问 quo 的 status 属性。get_status 无权访问参数的副本。它可以访问参数本身。这是可能的,因为该函数可以访问创建它的上下文。这称为闭包。
示例 2(第 39 页):
//make a function that assigns event handler function to array of nodes
//when you click on a node, an alert box will display the ordinal of the node
var add_the_handlers=function (nodes) {
var helper=function(i) {
return function(e) {
alert(i);
}
};
var i;
for (i=0;i<nodes.length;i++) {
nodes[i].onclick=helper(i);
}
};
我很难理解这段代码是如何工作的,而且函数(e)是做什么的?为什么辅助函数返回函数又什么都不返回。这让我很困惑。如果有人可以用简单的语言解释,那将非常有帮助。非常感谢
EDIT:
According to the book is the bad example for the above(example 2):
var add_the_handlers=function(nodes) {
var i;
for (i=0;i<nodes.length;i++) {
nodes[i].onclick=function(e) {
alert(i);
};
}
};
作者将此作为不好的例子,因为它总是显示节点的数量。