所以我试图定义一个类似于document.getElementById的函数g()。以下工作正常:
So I'm trying to define a function g() that is like document.getElementById. The following works just fine:
var g = function(id){return document.getElementById(id)};但为什么这个更直接的代码不起作用?
But why doesn't this more direct code work?
var g = document.getElementById;推荐答案
问题在于 context 。当您触发对象的函数时,它将使用该对象作为 this 的值触发(除非您另行指定)。 g = document.getElementById 将函数 getElementById 放入变量 g ,但没有设置上下文。
The problem is that of context. When you fire an object's function, it is fired with the object as the value of this (unless you specify otherwise). g = document.getElementById puts the function getElementById into the variable g, but doesn't set the context.
因此,当你运行 g(someId)时,那里没有函数可以运行的上下文。它使用全局对象窗口作为此的值运行,但这不起作用。 (确切地说,它不起作用,因为你可以使用任何文档对象,而不仅仅是 window.document ,你还没有指定一个。)
Therefore, when you run g(someId), there is no context on which the function can run. It is run with the global object window as the value of this, and that doesn't work. (To be precise, it doesn't work because you could be operating with any document object, not just window.document, and you haven't specified one.)
可以通过调用,你设置上下文:
You could get around this with call, where you set the context:
g.call(document, someId);但是,这不是原来的改进!
However, this isn't an improvement over the original!
更多推荐
为什么我不能直接将document.getElementById分配给不同的函数?
发布评论