以下是我的一个功能性 Express 应用程序,它连接到 mlab 上托管的数据库。但是,我对如何在代码的其他地方访问 MongoClient.connect 回调中定义的“db”变量感到困惑。连接函数中是否发生了一些我没有看到的魔法?请参阅下面的评论:
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
MongoClient.connect('link-to-my-db', (err, database) => {
if (err) return console.log(err);
db = database;
app.listen(3000, () => {
console.log("Listening on 3000");
});
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/quotes', (req, res) => {
// How is it possible for "db" to be accessible here even though it was defined in a separate function?
db.collection('quotes').save(req.body, (err, result) => {
if (err) return console.log(err);
console.log('saved to database');
res.redirect('/');
})
});
仅供引用:我正在学习 Node.js 的入门教程。我并没有神奇地编写上面的代码!
最佳答案
引用http://www.w3schools.com/js/js_scope.asp :
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
这意味着,由于 db
变量前面没有 var
关键字,因此它被隐式声明为全局变量,并且可以从其余变量访问您的应用程序。
关于javascript - 为什么在回调中定义的变量可以在代码中的其他位置访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516997/