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

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

    As lonesomeday's answer already shows, the problem is with the execution context. I would like to add that there is a way to create a function with the execution context. Open your browser's Developer Tools for this page and try the following in the Console:

    > document.getElementById('notify-container');
    // 
    > var _d = document.getElementById; // undefined > _d // ƒ getElementById() { [native code] } > _d('notify-container'); // Uncaught TypeError: Illegal invocation // at :1:1

    As before, directly invoking the variable _d which is assigned to document.getElementById fails. But you can use Function.prototype.bind to bind the execution context.

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    > var d = document.getElementById.bind(document);
    // undefined
    
    > d('notify-container');
    // 

    You also do not have to worry much about browser compatibility if you want to use bind: See https://caniuse.com/#feat=es5.

提交回复
热议问题