11

most javascript libraries contain lines similar to:

    var b = (a ? a.ownerDocument || a: 0).documentElement;

if a is null, what is (0).documentElement supposed to return?

4

4 回答 4

4

most probably: undefined what else?

于 2013-09-11T13:42:57.260 回答
4

From jQuery / Sizzle comments:

http://jsapi.info/jquery/1.7.2/jQuery.isXMLDoc

documentElement is verified for cases where it doesn't yet exist (such as loading iframes in IE - #4833)

So it's just cute syntax for returning undefined - this is a result of calling documentElement on 0.

In next line there is check:

return documentElement ? documentElement.nodeName !== "HTML" : false;

So it returns false anyway.

于 2013-09-11T13:44:45.057 回答
2

It's a shorthand for:

var b; // defaults to "undefined"
if (a) b = a.ownerDocument.documentElement || a.documentElement;

It is checking for whether the DOM documentElement has been created yet in the DOM tree. (0).documentElement accesses a non-existant property which defaults to undefined. If the "documentElement" is undefined, it has not been created yet.

This might be easier to visualize:

a.ownerDocument.documentElement || // try this first
a.documentElement || // fallback
undefined; //documentElement has not been created yet

It is not just "a cute syntax" like another answer suggested. It is "manual minification" because, in a dynamically typed language like JavaScript, a minifier cannot determine that "a" and "a.ownerDocument" might be of the same type and will therefore do little more than whitespace removal.

Running my above code through the Closure Compiler yields:

var b;a&&(b=a.documentElement||a.ownerDocument.documentElement);

Meanwhile, the "manually minified" version you presented in your question run through a minifier produces:

var b=(a?a.ownerDocument||a:0).documentElement;

Results:

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
于 2013-09-11T14:08:46.100 回答
0

The ownerDocument property returns the owner of document of a html node, as a document object. the html document itself is ownerDocument of an element. if it is null, i guess (0).documentElement return the initial document when page contains several documents. ownerdocument can be used to create html elments inside multiple documents in same page accordingly

于 2013-09-11T13:42:34.440 回答