获取 0 的文档元素返回什么
what does getting the documentElement of 0 return
大多数JavaScript库都包含类似于以下内容的行:
var b = (a ? a.ownerDocument || a: 0).documentElement;
如果a
null
,(0).documentElement
应该返回什么?
来自 jQuery
/Sizzle
评论:
http://jsapi.info/jquery/1.7.2/jQuery.isXMLDoc
在尚不存在的情况下验证 documentElement (例如在IE中加载iframe-#4833)
所以这只是返回undefined
的可爱语法 - 这是在0
上调用documentElement
的结果。
下一行有检查:
return documentElement ? documentElement.nodeName !== "HTML" : false;
所以它无论如何都会返回 false。
很可能
:未定义还有什么?
它是以下的简写:
var b; // defaults to "undefined"
if (a) b = a.ownerDocument.documentElement || a.documentElement;
它正在检查 DOM 文档元素是否已在 DOM 树中创建。(0).documentElement 访问默认为 undefined 的不存在的属性。如果"documentElement"未定义,则尚未创建。
这可能更容易可视化:
a.ownerDocument.documentElement || // try this first
a.documentElement || // fallback
undefined; //documentElement has not been created yet
它不仅仅是另一个答案所建议的"可爱的语法"。这是"手动缩小",因为在像 JavaScript 这样的动态类型语言中,缩小器无法确定"a"和"a.ownerDocument"可能属于同一类型,因此只会删除空格。
通过闭包编译器运行我的上述代码会产生:
var b;a&&(b=a.documentElement||a.ownerDocument.documentElement);
同时,您在问题中提出的"手动缩小"版本通过缩小器运行会产生:
var b=(a?a.ownerDocument||a:0).documentElement;
结果:
Without manual minification (my code) + Closure minifier: 64 characters
With manual minification (your original code): 54 characters
With manual minification (your original code) + Closure minifier: 47 characters
ownerDocument
属性返回 html 节点的文档所有者,作为文档对象。HTML 文档本身是元素的所有者文档。如果它是空的,我猜 (0).documentElement 在页面包含多个文档时返回初始文档。所有者文档可用于在同一页面的多个文档中相应地创建HTML文档
相关文章:
- 它将返回什么新日期(DateObject)
- 如果statusCode不是200,那么从http调用返回什么类型的错误对象
- Dijkstra的算法应该返回什么
- 具有多个返回语句的函数返回什么
- 如果未找到搜索方法,则应返回什么
- 如果字符串不匹配,.split() 返回什么
- querySelectorAll 和 getElementsBy* 方法返回什么
- 获取 0 的文档元素返回什么
- unescape()函数返回什么
- 我的函数应该通过.fail()回调为Ajax请求返回什么
- backbonejs入门-服务器应该返回什么
- 当index=-1时,JS在请求myArray[index]时返回什么
- 如果在已经是最后一个元素上调用jQuery.next方法,那么它会返回什么
- 从父函数返回什么以获取从子函数/嵌套函数返回的值
- getCurrentPosition返回什么
- 以下Javascript语句返回什么以及为什么返回
- String.charAt() 在给定一个无法解析为 int 的字符串的情况下返回什么
- 递归闭包返回什么?
- 对于非异步路径返回什么
- 在等待$onInit回调完成时,我应该为Angular绑定的属性返回什么?