Why can't I directly assign document.getElementById to a different function?

后端 未结 5 1961
悲&欢浪女
悲&欢浪女 2020-11-30 12:20

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.getElementB         


        
5条回答
  •  生来不讨喜
    2020-11-30 13:09

    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.

    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!

提交回复
热议问题