javascript - 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();
你心里有什么办法吗?
解决方案
您可以使用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();
推荐阅读
- html - 如何通过使用 CSS 将形状组合成一个来创建云?
- javascript - 单击时隐藏/显示部分表单。如何调试?
- ruby-on-rails - 如何通过从其他表中查找 id 来应用范围
- python - 以编程方式设置python路径
- javascript - 通过 Js 检索共享点列表
- javascript - 在这种情况下,你能在循环中返回一个布尔值吗
- haskell - 2019 年 Yesod 正则表达式
- python - 类之间的 NaN
- simulation - 如何在 Netlogo 中随时间改变海龟的颜色?
- javascript - 是否有任何内置函数,例如在 javascript 中查找所有内容?