【发布时间】:2016-09-28 14:20:00
【问题描述】:
我有来自here 的以下脚本:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
download('test.txt', 'Hello world!');
现在我不明白if (document.createEvent) 的用法:
我阅读了In JavaScript, does it make a difference if I call a function with parentheses? 问题的答案并阅读了其他一些问题。
在大多数示例中是某种引用,例如window.onload = initAll; 或var ret = Multiply;,但这里显然不是这种情况。对我来说最有趣的例子是:
function Multiply(operator, operand) {
return operator * operand;
}
var operator = 3;
var operand = 4;
var ret = Multiply;
这里,根据作者的说法,Multiply 没有被执行,ret 引用了函数Multiply。
另外here 声明调用不带括号的函数是一个引用。
但这让我更加困惑,因为对我来说,引用 document.createEvent(这是一个创建事件的函数)没有意义。
关于函数document.createEvent()如here的文档没有指出没有参数的用法。
所以,请给我黑暗的大脑带来一些光明。 感谢您的帮助。
问题(简短):
-
document.createEvent是函数调用还是引用? -
document.createEvent返回什么?
【问题讨论】:
-
检查document.createEvent函数是否存在。它根本不叫它。在 Javascript 中,函数是一等对象,可以这样对待。
-
它正在检查浏览器是否支持
document.createEvent,如果支持则使用它,否则使用不同的方法。 -
JavaScript If statement condition with no operator? What does it do? 的可能副本—— 这完全是相同的技术。
标签: javascript