我正在尝试做一些相当简单的事情:
我有一个属于某个类的函数,在这个函数中我调用了
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 调试器可能有问题?所以毕竟,代码似乎没有任何问题......
最佳答案
你有三个不同的箭头函数,它们都没有尝试使用 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/