如何修复下面的代码,以便能够使用 call
调用类方法。
类定义:
class User {
constructor(..) {...}
async method(start, end) {}
}
尝试将类方法作为函数参数传递:
const User = require('./user');
async function getData(req, res) {
// User.method is undefined, since User refers to User constructor
await get(req, res, User.method);
}
async function get(req, res, f) {
let start = ...;
let end = ...;
let params = ...;
let user = new User(params);
// f is undefined here
let stream = await f.call(user, start, end);
}
最佳答案
User method is undefined, since User refers to constructor
你正在寻找User.prototype.method
:
async function getData(req, res) {
await get(req, res, User.prototype.method);
}
请记住,ES6 类是语言原型(prototype)性质之上的语法糖。
关于javascript - 将 ES6 类方法作为要在函数内部调用的函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285999/