我对这个小片段有疑问:
<script>
function download() {
alert('Hi');
}
</script>
<a href="#" onClick="javascript:download();">Test</a>
一旦我在 Chrome 14.0 中点击链接,我会得到一个
Uncaught TypeError: string is not a function
在 Firefox 和 IE 中它工作得很好。我通过重命名函数解决了这个问题,但我仍然很好奇 Chrome 中的“下载”是什么。据我所知,它不是保留关键字,它可能是什么?
最佳答案
<a>
元素有一个 download
HTML5 中的属性说明 here , 默认值为 ""
(空字符串)。
这意味着download === this.download
在onclick
处理程序( this
是 onevent
属性中的元素),因此 download
元素的属性优于 download
window
的属性(property).
This fiddle列出默认存在的所有字符串属性。可以看到download
是一个属性,就像 innerHTML
,这also fails用作函数时具有完全相同的原因(即尝试引用 window.innerHTML
,而不是执行 elem.innerHTML()
)。
如评论中所述,使用 window
不会混淆属性/属性变量的计算结果。
这个范围行为实际上似乎不是由于 this
值(value),而是正在构建的特定“作用域链”。
Lexical Environment Scope
Let
Scope
be the result ofNewObjectEnvironment(the element's Document, the global environment)
.If the element has a form owner, let
Scope
be the result ofNewObjectEnvironment(the element's form owner, Scope)
.Let
Scope
be the result ofNewObjectEnvironment(the element's object, Scope)
.
即正在发生的是作用域链是 window
-> document
-> element
(增加优势)。这意味着 download
评估为 element.download
而不是 window.download
.由此还可以得出的结论是getElementById
会冒泡到document.getElementById
(给定 elem.getElementById
不存在)。
我设置了a systematic example这样你就可以看到变量是如何在作用域链中冒泡的:
window.a = 1;
document.a = 2;
elem.a = 3;
window.b = 4;
document.b = 5;
window.c = 6;
然后,<a ... onclick="console.log(a, b, c)">
日志 3
, 5
, 6
单击时。
关于javascript - 不能在 javascript 中使用 "download"作为函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7852237/