Reputation: 13
I have 2 files below
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: ''})
I need to have index.conn
object to be assigned under new index.transaction()
, when newly instantiated. So that, code below would work
let transaction = new index.txn({ data: 'here' });
transaction.startTransaction();
Any possible way in your mind?
Upvotes: 0
Views: 81
Reputation: 1337
You can use Function.prototype.bind to pass the connection to the transaction:
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
*/
}
}
And run
let index = new Index({url: ''});
let transaction = new index.txn({ data: 'here' });
transaction.startTransaction();
Upvotes: 1
Reputation: 894
Transaction.js
class Transaction {
constructor (txn) {
this.txn = txn;
}
startTransaction (conn) {
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;
}
startTransaction (){
this.txn.startTransaction(this.conn);
}
}
let index = new Index({url: ''})
Then run
let index = new index.txn({ data: 'here' });
index.startTransaction();
Upvotes: 0