Short variable for DOM methods

前端 未结 2 925
臣服心动
臣服心动 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:13

    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.

提交回复
热议问题