Why can't I have a direct reference to document.createElement?

后端 未结 1 1286
后悔当初
后悔当初 2021-01-20 14:15

When creating lots of DOM elements, document.createElement and friends can add lots of bytes and ugliness. I know I could make my own subroutine, or use innerHTML or whateve

相关标签:
1条回答
  • 2021-01-20 14:27

    The way you are invoking it, causes the this value inside the createElement method to refer to the global object.

    I would recommend you to simply use a function:

    var $c = function (tagName) { return document.createElement(tagName); };
    var newP = $c('p');
    

    The behavior I talk can be described with an example:

    var foo = 'global foo';
    
    var obj = {
      foo: "I'm obj.foo",
      method: function () {
        return this.foo;
      }
    };
    
    
    var fn = obj.method;
    
    obj.method(); // "I'm obj.foo"
    fn();         // "global foo"
    
    0 讨论(0)
提交回复
热议问题