Javascript 扩展继承

标签 javascript inheritance ecmascript-6

我有以下 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: ''})

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

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

你有什么可能的办法吗?

最佳答案

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

transaction.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();

关于Javascript 扩展继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51321861/

相关文章:

Javascript list : Edit and Delete button

javascript - 如何使用 jQuery 从 AJAX 请求获取响应文本

Javascript 发布数组显示语法错误

c++ - 组合与继承——抽象类

c# - 具有相同泛型方法的抽象类和接口(interface)

javascript - 更新 React Redux 中的深层嵌套状态(标准化)

javascript - 在页面上引导多个 Angular 应用程序会导致 Controller 未定义的错误

javascript - 无法使用 Node.js 和 Express 捕获 POST 参数

c++ - 构造调用顺序 (C++)

javascript - javascript 中日期范围内的每小时分钟数