【发布时间】:2019-02-13 06:53:19
【问题描述】:
由于app.populateDatabase 内部的无上下文调用,此示例中的函数doSomethingElse 无法执行,因为它的this 已被重新绑定到window 或global(如果在Node 中)。
有没有办法避免这种情况而不在每个函数中引用app?
loadDatabase函数根据逻辑语句执行回调,如果虚构的数据库不存在,加载后填充,然后populateDatabase执行已提供的回调。
我无法将onLoaded 参数重新绑定到app,因为我不知道它来自哪里,并且过度使用绑定/应用/调用抽象会造成相当混乱。
var app = {};
app.loadDatabase = function(onLoaded) {
// If database already exists, only run a callback
var callback = onLoaded;
// If database doesn't exists, populate it, then run a callback.
if (!databaseExists) {
callback = this.populateDatabase.bind(this, onLoaded);
}
this.database = new sqlite.Database("file.db", function(error) {
if (error) { ... }
callback();
})
}
app.populateDatabase = function(onPopulated) {
// Contextless call here. <--------
onPopulated();
}
app.doSomethingElse = function() {
// this != app due to contextless call.
this.somethingElse();
}
app.run = function() {
// Load the database, then do something else.
this.loadDatabase(this.doSomethingElse);
}
app.run();
【问题讨论】:
-
然后使用 ES6 箭头函数(它们自己没有
this)。 -
@connexo 这到底有什么帮助?我使用
this来引用app而没有实际命名它。 -
这意味着该函数将具有在调用之外可用的
this。 -
另一种选择是将
.bind(app)添加到您希望this始终指向app的任何函数定义中。
标签: javascript function function-binding