Why don't I have a direct link to document.createElement?

When creating a large number of DOM elements, document.createElement and friends can add a lot of bytes and ugliness. I know that I can make my own routine or use innerHTML or something else, but why not just do this:

var $c = document.createElement;
var newP = $c('p');

Firebug complains about this post:

"Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"

It is clear that I did something that is not allowed. Why not? This allowed for other things, for example. Array.splice or Math.min.

+3
source share
1 answer

As you call it, the value thisinside the method createElementrefers to the global object.

I would recommend you just use the function:

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

, , :

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"
+8

Source: https://habr.com/ru/post/1769049/


All Articles