为什么不能将`document.getElementById`设置为全局变量?

it_*_*ure 0 javascript

对于这里的代码结构

var mydo=sessionStorage.getItem("action");
function to_delete(){
    var _table=document.getElementById("showTable");
    //omit
    }
window.onload=function(){
    to_delete();
    }
Run Code Online (Sandbox Code Playgroud)

我得到了理想的结果.现在重写代码结构如下:

var mydo=sessionStorage.getItem("action");
var _table=document.getElementById("showTable");
function to_delete(){
    //omit
    }
window.onload=function(){
    to_delete();
    }
Run Code Online (Sandbox Code Playgroud)

发生错误, TypeError: _table is null.
为什么不能设置document.getElementById为全局变量?

Ale*_* K. 5

var _table=document.getElementById("showTable");文档加载之前的重写运行中,因此元素不存在.

而是var _table;在函数外部声明全局,并在load事件中为其赋值.