javascript - 为什么在回调中定义的变量可以在代码中的其他位置访问?

标签 javascript node.js mongodb express

以下是我的一个功能性 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/

相关文章:

node.js - 使用 $min 选择字段的最小值并在 mongodb 中聚合

javascript - 嵌套在 Foreach 中的 Map 函数未按预期运行 为什么?

javascript - 用 JSON 数据填充多个选择框

javascript - 在 ASP.Net 中使用 AJAX PageMethods 从数据库中进行 JQuery AutoComplete TextBox 无法在 Internet Explorer 中工作

node.js - Docker多阶段构建分支而不是链

mysql - 无法与 LoopBack 建立 MySql 连接

python - 如何使用 PyMongo 在重复键错误后继续插入

javascript - 为什么每次请求都会发送 cookie,但在浏览器控制台或 document.cookie 中看不到?

ios - 我如何使用 Alamofire 进行基于 token 的身份验证?

MongoDB 文本索引多词搜索太慢