javascript - 装饰在 Vue 中调用的函数弄乱了 'this' 绑定(bind)?

标签 javascript vue.js decorator

我的 Vue 应用程序使用普通 JS 对象来集中数据库调用。我想控制台记录调用。为此,我正在装饰对象的方法,如下所示:

const Caller = {
    callingDB (arg1, arg2) { return ... } //Promise-wrapped db call here
}
const decorator = f => (...args) => {
    return f(...args).then(res => console.log(`Invoked method ${f.name} with ${args} for result: ${res}`))
}

Caller.callingDB = decorator(Caller.callingDB)

在几个 Vue 组件中,我有调用上述普通对象方法的组件方法: ...

methods: {
 cMethod() { this.Caller.callingDB(arg1, arg2) }
}

但有一个警告:一旦装饰了 Caller.callingDB 方法,就会由于“this”未定义而引发错误——我的应用程序中的数据流在这里和那里依赖于通过上述方法进行的链式数据库调用,所有这些都以类似的方式调用。没有装饰一切正常。

我不明白为什么会出现这些错误。关于我应该如何重写我的装饰器以保留所有后续的 this-bounded 调用的任何提示?还是我错过了这些错误背后的罪魁祸首?

最佳答案

const decorator = f => (...args) => {
    return f.apply(Caller, args).then(res => console.log(`Invoked method ${f.name} with ${args} for result: ${res}`))
}

js 中的函数有 apply 方法,它接受 this 值作为第一个参数,arguments 数组作为第二个参数。

这是修改后的代码的 fiddle https://jsfiddle.net/435h2gwp/

关于javascript - 装饰在 Vue 中调用的函数弄乱了 'this' 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201133/

相关文章:

javascript - 统一 CSS - 在选择框右侧添加图标

javascript - 从 firestore 中的集合中获取数据

javascript - v-for 基于 v-model 值的项目

Python 装饰器? - 有人可以解释一下吗?

javascript - 自定义plotly.js图例的外观

c# - 将参数发送到 jQuery 的 Ajax 无效

python - 仅在 python 中使用装饰器进行 POST 请求

javascript - "this"引用如何在以下函数中传输

javascript - 使用 JavaScript 从变量中获取 getElementById

javascript - 从动态创建的函数调用时全局变量不可用