javascript - 将 ES6 类方法作为要在函数内部调用的函数参数传递

标签 javascript ecmascript-6

如何修复下面的代码,以便能够使用 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/

相关文章:

javascript - React,单击时获取列表索引

javascript - 开 Jest - 测试 mobx store @action TypeError : is not a function

javascript - Express 路由器回调中 Array.includes() 始终为 false,Array.indexOf() 始终为 -1 且 Array.find() 始终未定义

javascript - 访问数组中的单个项并将它们添加到总变量

javascript - 在 jquery twitter bootstrap 向导上隐藏药丸

javascript - 将 Parantsis 之间的字符串插入数组数组时遇到问题

javascript - 自动绑定(bind)JS类方法有什么好方法?

cordova - cordova 是否支持 ES6 和/或 Angular2?

svg - 将 es6 中的 svg-pan-zoom 与 webpack 结合使用

javascript - 访问函数范围之外的变量但不使其成为全局变量(window.hazaa)?