【发布时间】:2018-02-26 22:18:44
【问题描述】:
我有这个网页,我必须使用很多 document.getElementById's。由于我很懒,我想通过将document.getElementById 分配给一个较短的变量来节省几个字节:
var geid = document.getElementById;
但是,这并没有按我的预期工作。它给了我以下错误:
未捕获的类型错误:非法调用
考虑以下证明我的问题的 sn-p:
var foo = document.getElementById('foo');
console.log(foo); // outputs: '<div id="foo">Foo</div>'
var geid = document.getElementById;
var foo_geid = geid('foo'); // Aaaaaargh! Uncaught TypeError: Illegal invocation
console.log(foo_geid);
<div id="foo">Foo</div>
那我做错了什么?为什么我不能做我做过的事?
我检查了“How does the "this" keyword work?”,因为我有一种预感,this 必须与这一切有关。 (在我看来,getElementById 以某种方式从document 对象中分离)。但我无法真正查明和阐明问题。谁能帮帮我?
【问题讨论】:
-
也许你应该考虑用谷歌搜索错误信息。 This seems to explain the problem
-
你必须将文档绑定到它
-
@musefan:对不起,我真的没有谷歌它。因为我知道答案。我遇到了stackoverflow.com/questions/9677985/…,但它没有我想要的答案。我一直在寻找解释 JavaScript 执行上下文的答案。
标签: javascript object binding this