本文介绍了为什么我不能直接引用document.createElement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当创建大量DOM元素时,document.createElement和朋友可以添加很多字节和丑陋。我知道我可以做自己的子例程,或者使用innerHTML或者其他的东西,但为什么我不能这么做:

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 whatever, but why can't I just do this:

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

Firebug抱怨此消息:

Firebug complains with this message:

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

显然,我做了不允许的事情。为什么不呢允许其他的东西,例如Array.splice或Math.min。

Clearly I've done something that is Not Allowed. Why isn't it? It's allowed for other things, e.g. Array.splice or Math.min.

推荐答案

您调用它的方式导致 / code> value里面的 createElement 方法来引用全局对象。

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"

这篇关于为什么我不能直接引用document.createElement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:12