Short variable for DOM methods

前端 未结 2 922
臣服心动
臣服心动 2021-01-21 10:46

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

<
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 11:06

    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);
    }
    

提交回复
热议问题