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

后端 未结 5 1958
悲&欢浪女
悲&欢浪女 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:10

    Because when you call "g('somestr')" the "this" value is bound to the "window" and "document.getElementById" seens to expect to be bound to "document" instead "window"(makes sense to me =) ). Doing:

    var g = document.getElementById;
    g('somestr');
    

    is like:

    document.getElementById.call(window, 'somestr');
    

提交回复
热议问题