首页 > 解决方案 > Javascript扩展继承

问题描述

我在下面有 2 个文件

transaction.js

class Transaction {
  constructor (txn) {
    this.txn = txn;
  }
  startTransaction () {
    this.conn.send(this.txn);
  }
}

index.js

const Transaction = require('./transaction')
class Index {
  constructor(option = {}) {
    this.conn = this.setConnection(option.url); // { url: '', send: [Function] }
    this.txn = Transaction;
  }
}
let index = new Index({url: ''})

新实例化时,我需要在index.conn下分配对象。new index.transaction()这样,下面的代码就可以了

let transaction = new index.txn({ data: 'here' });
transaction.startTransaction();

你心里有什么办法吗?

标签: javascriptinheritanceecmascript-6

解决方案


您可以使用Function.prototype.bind将连接传递给事务:

交易.js

class Transaction {
    constructor (conn, txn) {
        this.conn = conn;
        this.txn = txn;
    }
    startTransaction () {
        this.conn.send(this.txn);
    }
}

index.js

class Index {
    constructor(option = {}) {
        this.conn = this.setConnection(option.url); // { url: '', send: [Function] }
        this.txn = Transaction.bind({}, this.conn); /*
                                                       .bind() here will create a new function
                                                       that ensures this.conn will be passed as the
                                                       first argument to Transaction
                                                     */
    }
}

并运行

let index = new Index({url: ''});
let transaction = new index.txn({ data: 'here' });
transaction.startTransaction();

推荐阅读