Can a \"shortcut\" not be made to methods such as document.createElement
, document.createTextNode
, [element].setSelectionRange
etc?
There are two obvious issues:
this
value (it will be the global object rather than document
), which the DOM method may or may not depend upon;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);
}
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.