0

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?

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I need! Thanks :D
0

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

1 Comment

thanks for the answer :D but I feel @Hyddan answer above is more appropriate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.