开发者

Short variable for DOM methods

Can a "shortcut" not be made to methods such as document.createElement, document.createTextNode, [element].setSelectionRange etc?

var c = document.createElement;
var div = c('div');
div.innerHTML = 'blah';

document.body.appendChild(div);

When executing the above code Firebug console returns an error:

uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVE开发者_如何学运维RT_JS)" location: "JS frame :: http://fiddle.jshell.net/_display/ :: :: line 20" data: no]

This happens on jsfiddle as provided here and silently fails when done outside of jsfiddle with no errors.

The below code works fine, so is it just limited to DOM manipulation methods?

function long_function_name(prop)
{
   alert(prop);
}

var c = long_function_name;

c('blah');

This has practical examples for compression sake:

Instead of:

if (element.setSelectionRange)
{
    element.setSelectionRange(pos, pos);
}

Compress to:

var s = element.setSelectionRange || 0;
if (s) s(pos, pos);


In JavaScript, calling document.createElement calls the .createElement method with this = document. When you assign it to a variable, it loses this association.

You have to write a short function to call the method properly. For example:

var c = function(name){ return document.createElement(name); };

In newer versions of ECMAScript used by some browsers, you have the easier option of

var c = document.createElement.bind(document);

Unfortunately this is not universally supported.


There are two obvious issues:

  • Calling your aliased functions will not be providing the correct this value (it will be the global object rather than document), which the DOM method may or may not depend upon;
  • DOM nodes in JavaScript are host objects, which are not subject to the normal rules of native JavaScript objects and can essentially do what they like. For example, there is no guarantee that a method of a host object is a regular Function object and may not therefore have the call() or apply() methods that you could otherwise use to provide the correct this value.

This being the case, you're better off writing a wrapper function instead, such as

function c(tagName) {
    return document.createElement(tagName);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜