我有以下 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/