gpt4 book ai didi

javascript - 无法从 javascript 书中理解这些示例,好的部分

转载 作者:行者123 更新时间:2023-12-03 11:15:58 25 4
gpt4 key购买 nike

<分区>

我正在阅读 javascript:Douglas Crockford 的精彩部分。我在理解特定示例和作者提供的解释时遇到困难。

示例 1:(第 38 页)

var quo=function (status) {
return {
get_status:function() {
return status;
}
};
};

var myQuo=quo("amazed");
document.writeln(myQuo.get_status());

书上的解释(这个我没看懂,请解释这部分):

This quo function is designed to be used without the new prefix, so the name is not capitalized.when we call quo, it returns a new object containing a get_status method. A reference to that object is stored in myQuo. The get_status method still has privileged access to quo's status property even though quo has already returned. get_status does not have access to a copy of the parameter. it has access to the paramter itself. This is possible because the function has access to the context in which it was created. This is called closure.

示例 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);
}
};

我很难理解这段代码是如何工作的,而且 function(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);
};
}
};

作者将此作为错误示例引用,因为它始终显示节点数。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com