1,this指向问题的代码:
var _getElementById = document.getElementById; document.getElementById = function(id){ console.log(1); return _getElementById(id); } var button = document.getElementById( 'button' ); //Uncaught TypeError: Illegal invocation at HTMLDocument.document.getElementById (<anonymous>:5:12) at <anonymous>:8:23
异常发生在_getElementById(id)这句,此为一个全局函数,调用全局函数时候this指向是window,而document.getElementById内部实现this指向是document。所以需要在调用时候将this指向document对象。改动后代码如下:
document.getElementById = function(){ console.log(1); return _getElementById.apply(document,arguments); } var button = document.getElementById( 'button' );
【不定期更新中】