为什么即使对象未在 javascript 代码中定义,此代码也能正常工作

Why does this code work even though the object is not defined in the javascript code?

本文关键字:代码 常工作 工作 定义 对象 为什么 javascript      更新时间:2023-09-26

我正在使用JSLint,它说:"matte_canvas"没有定义。显然,在我的 javascript 代码中,我没有定义"matte_canvas",但是,它确实在控制台中输出了 canvas 元素。

这是我的代码:

.HTML:

<canvas id="matte_canvas" width="50" height="50" style="background-color:blue;"></canvas>

Javascript:

console.log(matte_canvas);

这是在JSFiddle上:http://jsfiddle.net/allisonc/rqo5a417/

有人可以向我解释一下它是如何工作的吗?

>id也是全局变量(如果没有为它们分配其他值)。不要依赖这个。这也适用于某些元素的 name 属性:aappletareaembedformframesetimgobject

alert(window.matte_canvas);

更多信息: https://html.spec.whatwg.org/multipage/nav-history-apis.html#named-access-on-the-window-object