bra*_*orm 2 javascript function object
我正在阅读javascript:Douglas Crockford的优点.我很难理解一个特定的例子和作者提供的解释.
例1 :(第38页)
var quo=function (status) {
return {
get_status:function() {
return status;
}
};
};
var myQuo=quo("amazed");
document.writeln(myQuo.get_status());
Run Code Online (Sandbox Code Playgroud)
书中的解释(我不明白这一点.请解释这一部分):
这个quo函数被设计为在没有新前缀的情况下使用,因此名称不是大写的.当我们调用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);
}
};
Run Code Online (Sandbox Code Playgroud)
我很难理解这段代码是如何工作的,而且函数(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);
};
}
};
Run Code Online (Sandbox Code Playgroud)
作者将此列为坏示例,因为它始终显示节点数.
我相信,他在示例中暗示的是,您不必复制status参数并将其传递给get_status函数,因为get_status隐式地访问了在其定义的上下文中包含的所有内容(在这种情况,quo)
类似地,在示例2中

| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |