代码之家  ›  专栏  ›  技术社区  ›  Bram Vanbilsen

在胖箭头函数中未定义,但在封闭范围中定义

  •  2
  • Bram Vanbilsen  · 技术社区  · 8 年前

    我有一个函数是类的一部分,在这个函数中我调用 .then 用于侦听其完成的语法。我 然后使用箭头函数执行操作。

    this 根据VS代码调试器未定义。但是, 在函数中定义 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);
                });
            });
        }
    }
    

    这 从定义箭头函数的范围开始。但也许我误解了?我主要是和Dart一起工作,在Dart中范围规则并没有那么复杂,所以也许我把一些东西和Dart混在一起了?

    --编辑-- 对不起,我真的不需要 在我的arrow函数中,但是对于VS代码调试器将其显示为 undefined enter image description here

    1 回复  |  直到 8 年前
        1
  •  1
  •   Quentin    8 年前

    你有三个不同的箭头函数,但没有一个试图使用 this

    实际上,我在任何箭头函数中都不需要这样做,但是在调试时,我发现由于某种原因,在它们的作用域中这是未定义的。

    这是性能优化。

    如果一个变量没有在函数中使用,那么它将不存在于该函数中,即使它本来就在作用域中。

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

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

    这 .

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

    推荐文章