javascript - 这在粗箭头函数中未定义,但在封闭范围内定义

标签 javascript node.js ecmascript-6 es6-promise

我正在尝试做一些相当简单的事情:

我有一个属于某个类的函数,在这个函数中我调用了 async 方法,我使用 .then 语法来监听它的完成。我 然后使用箭头函数执行操作。

这是我的箭头函数中出现问题的地方,this 根据 VS 代码调试器未定义。但是,this 是在函数中定义的 (write(document)) 包含箭头函数。

代码如下:

const fs = require('mz/fs');
const path = require('path');

class DB {

    constructor(name) {
        this.db = path.normalize("./");
    }

    write(document) {
        const dir = path.normalize(this.db + "/" + document);
        fs.exists(dir).then((exists) => {
            console.log(this); // ADDED THIS IN EDIT.
            if (!exists) {
                return fs.mkdir(dir)
            } else {
                return new Promise();
            }
        }).then(() => {
            const file = path.normalize(dir + "/" + document + ".json");
            fs.readFile(file, (err) => {
                console.log(err);
            });
        });
    }
}

我以为已经读到箭头函数从定义箭头函数的范围自动绑定(bind)this。但也许我误解了?我主要使用 Dart,其中的范围规则并不那么复杂,所以也许我将某些东西与 Dart 混在一起了?

--编辑-- 很抱歉造成混淆,实际上我的箭头函数中不需要 this,但令我惊讶的是 VS Code 调试器将它显示为 undefined。我现在在箭头函数中添加了一个控制台日志,显然它已被定义!因此,VS 代码 Node 调试器可能有问题?所以毕竟,代码似乎没有任何问题...... enter image description here

最佳答案

你有三个不同的箭头函数,它们都没有尝试使用 this

I actually do not need this in any of the arrow functions, but upon debugging I found that this is undefined in their scope for some reason.

这是一项性能优化。

如果一个变量没有在一个函数中使用,那么它就不会存在于那个函数中,即使它本来在范围内也是如此。

这允许,例如:

function foo () {
    var bar = something_that_returns_a_memory_intensive_object()
    return () => console.log(1);
}

const baz = foo();

foo 完成运行并返回其函数后,bar(和大对象)可以被垃圾回收。

this也是如此。

I now added a console log in the arrow function and apparently it is defined!

…当你使用它时,变量被关闭并可用。

关于javascript - 这在粗箭头函数中未定义,但在封闭范围内定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51966312/

相关文章:

javascript - 正则表达式/_/g 是什么意思?

javascript - 从网站(livebox)提取数据

javascript - 类型错误 : Converting circular structure to JSON

node.js - Socket.IO + Express 框架 |从 Express Controller 和路由器发射/发射

javascript - 对所有消息使用单个 React-Toastr 容器

javascript - 如何展平嵌套的 JSON?

node.js - 运行 react 应用程序时出错

javascript - 添加几个类实例到 'container'类属性对象

javascript - 通过键比较将一个对象复制到另一个对象

javascript - 从 JavaScript 触发服务器端电子邮件,无需回发