避免在ES6中正确绑定到类的hacks?

时间:2016-12-27 03:55:47

标签: javascript ecmascript-6 es6-class

我觉得这很麻烦。我可能做错了或者有一些我不知道的更简单的方法(没有找到太多知道要搜索的内容)。

我想避免执行以下两种解决方法,以确保this正确指向我方法中的DB类:

this.connect = this.connect.bind(this);
db.connect.bind(db)

数据库类:

'use strict';

const http = require('http');
const MongoClient = require('mongodb').MongoClient;

class DB {
  constructor(opts){
    this.opts = opts;
    this.dbUrl = process.env.MONGODB_URL;

    // anyway to avoid this hacK?
    this.connect = this.connect.bind(this);
    this.close = this.close.bind(this)
  }

  async connect(ctx, next){
    try {
      ctx.db = await MongoClient.connect(this.dbUrl); // fixes `this` being incorrect here
    } catch(err) {
      ctx.status = 500;
      ctx.body = err.message || http.STATUS_CODES[ctx.status];
    }

    await next();
  }

  async close(ctx, next){
    const result = await ctx.db.close();
    await next();
  }
}

module.exports = DB;

调用DB类方法db.connect()

'use strict';

const Koa = require('koa');
const DB = require('./db');
const db = new DB();
const bodyParser = require('koa-bodyparser');
const router = require('koa-router');

const api = router();
const app = new Koa();
const cors = require('kcors');

app
  .use(bodyParser())
  .use(cors())
  .use(db.connect); // the above constructor copying fixes having to do `db.connect.bind(db)` here

  // without the constructor fix in class DB:

  .use(db.connect.bind(db)) // this gets annoying having to do this everywhere

哪个更“正确”,或者是否有第三种方法可以避免这两种解决方法?如果这些是将类方法绑定到类的唯一两种方法,那么每种方法的优点和缺点是什么。

1 个答案:

答案 0 :(得分:0)

有一系列有用的自动绑定功能。我今天写了一篇文章来改进它们。看看:https://www.npmjs.com/package/auto-bind-inheritance

npm install --save auto-bind-inheritance

const autoBind = require('auto-bind-inheritance');

只需将autoBind(this);放在子类构造函数中,所有方法和方法指针都将绑定到对象,就像您在C ++ / Java中所期望的那样。这基本上会为您调用bind

所以,如果你在使用方法作为回调绑定到另一个'this'时遇到问题,这个包将修复它。