疑惑 JS 犀牛书 创建节点方便方法

puhjack 2011-10-05 11:17:43
犀牛书中
Page 338

源代码:
function make(tagname, attributes, children) {

// If we were invoked with two arguments the attributes argument is
// an array or string, it should really be the children arguments.
if (arguments.length == 2 &&
(attributes instanceof Array || typeof attributes == "string")) {
children = attributes;
attributes = null;
}

// Create the element
var e = document.createElement(tagname);

// Set attributes
if (attributes) {
for(var name in attributes) e.setAttribute(name, attributes[name]);
}

// Add children, if any were specified.
if (children != null) {
if (children instanceof Array) { // If it really is an array
for(var i = 0; i < children.length; i++) { // Loop through kids
var child = children;
if (typeof child == "string") // Handle text nodes
child = document.createTextNode(child);
e.appendChild(child); // Assume anything else is a Node
}
}
else if (typeof children == "string") // Handle single text child
e.appendChild(document.createTextNode(children));
else e.appendChild(children); // Handle any other single child
}

// Finally, return the element.
return e;
}


/**
* maker(tagname): return a function that calls make() for the specified tag.
* Example: var table = maker("table"), tr = maker("tr"), td = maker("td");
*/
function maker(tag)
{
return function(attrs, kids)
{
if (arguments.length == 1) return make(tag, attrs);
else return make(tag, attrs, kids);
}
}

中红色标记部分,疑惑描述:
function maker( tag ) // 此处的入口参数就是一个
{
return function( attrs, kids ) // 此处从何得来两个入口参数 ???
{
// 经过测试在该区域块中能取得的数据也只有 tag 如何会有attrs kids
if( argument.length == 1 )
{
return make( tag, attrs ); // attrs 从哪里来的 ???
}
else
return make( tag, attrs, kids ); // kids 又是从哪里来的 ???
}
}

再次先感谢大家的帮助
...全文
141 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
puhjack 2011-11-06
  • 打赏
  • 举报
回复
3Q3Q
人言谦德自然得分,某人傲言不予理睬
lsw645645645 2011-10-05
  • 打赏
  • 举报
回复
这个,只是个函数返回函数嘛。
举个例子

//我定义一个输出人名字的函数
function people(name) {
alert(name);
}
//调用
people('jack'); //jack

//这个时候,客户要求,还要加上年龄,和身高。函数名不能改,参数也不能动。因为客户端已经在使用这个函数了。。你要怎么办?
function people(name) {
return function (age,height) {
alert(name + ',' + age+','+'height');
}
}
//调用
var people = people('jack');
people(26, '176cm');//输出jack,26,176cm

KK3K2005 2011-10-05
  • 打赏
  • 举报
回复
[Quote=引用楼主 puhjack 的回复:]
function maker( tag ) // 此处的入口参数就是一个
{
return function( attrs, kids ) // 此处从何得来两个入口参数 ??? 看清楚了是一个函数定义(这个函数接受2个参数) return后面跟一个函数定义是什么意思呢(这个自己回答)?
下面的问题 借鉴此回答
{
// 经过测试在该区域块中能取得的数据也只有 tag 如何会有attrs kids
if( argument.length == 1 )
{
return make( tag, attrs ); // attrs 从哪里来的 ???
}
else
return make( tag, attrs, kids ); // kids 又是从哪里来的 ???
}
}
[/Quote]
有些东西不是问题 我只能说 你看的太快了
基础掌握了才能看后面的东西

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧