我正在学习关于AJAX的教程,制作视频的人做了一些奇怪的事情.至少我以前没见过.他们将对象属性设置为等于函数名称,但没有熟悉的().后来他继续定义了这个功能.代码在下面提供了上下文.无论如何,设置一个没有参数的函数是什么意思?这行代码确实正在运行名为的函数,如下所示.
xmlHTTP.onreadystatechange = handleServerResponse;
Run Code Online (Sandbox Code Playgroud)
有一个名为"handleServerResponse()"的函数,该行实际运行.我可以发布它,但我认为这是无关紧要的.这只是一个正常的功能function handleServerResponse().任何解释将不胜感激!谢谢!〜Carpetfizz
编辑:添加()到该行的末尾,创建错误,以及更改它.
我们使用()来调用函数,但我很困惑为什么我们在javascript中的onclick事件中附加函数时只使用函数名.
function a(){
alert(0)
}
document.getElementById('btn').onclick=a
<input value="click" type="button" id="btn" />
Run Code Online (Sandbox Code Playgroud) 效率上有区别吗?如果使用setTimeout代替console.log(),行为是否会有所不同?
我发现这个浏览:
在那里阅读答案后,我不理解函数引用和函数调用的定义和用法.然后我搜索了很多,但目前还不清楚在哪里使用什么.
你可以通过指出概念和用法的不同来帮助我理解这一点吗?我想把它作为未来程序员的参考.
我读StackOverflow上的答案在这里解释了如何使用的setTimeout来创造一种在网页上反复循环。但是,我想知道为什么 setTimeout 需要匿名函数才能工作。考虑以下代码:
trainingTimer(60,0);
function trainingTimer(duration,c) {
document.getElementById("timer").innerHTML = "Time left: "+(duration-c);
if(duration==c) {
alert("Time is up!");
}
else {
window.setTimeout(trainingTimer(duration,c+1),1000);
}
}
Run Code Online (Sandbox Code Playgroud)
我是根据上面链接的答案写的,但是当它运行时,它会trainingTimer一次遍历所有 60 个调用,并立即在我的网页上显示“剩余时间:0”。但是,如果我修改
window.setTimeout(trainingTimer(duration,c+1),1000);
并trainingTimer(duration,c+1)像这样包装一个匿名函数
window.setTimeout(function() {trainingTimer(duration,c+1)},1000);
那么代码工作得很好。
我想知道为什么我必须将命名函数包装在匿名函数中才能使 setInterval 正常工作。感谢所有的帮助。
我运行这个脚本来使用 mongoose 连接到 MongoDB。
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/curious", { useNewUrlParser: true });
const db = mongoose.connection;
const dbLog = (msg) => {
console.log(`[DATABASE] [SUCCESS] ${msg}`);
}
const dbLogError = (msg) => {
console.error(`[DATABASE] [ERROR] ${msg}`);
}
db.on("error", dbLogError("Database connection failure"));
db.once("open", () => {
dbLog("Database connection successful");
})
mongoose.connection.close()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
PS D:\scripts> node .\dbUtils.js
[DATABASE] [ERROR] Database connection failure
events.js:110
throw new ERR_INVALID_ARG_TYPE('listener', 'Function', listener);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined
at …Run Code Online (Sandbox Code Playgroud) javascript ×6
ajax ×1
es6-promise ×1
function ×1
mongodb ×1
mongoose ×1
node.js ×1
setinterval ×1