Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass methods of JS objects?

Tags:

javascript

When passing an object method as a function argument, I have to use `bind' to make sure the context (this) of the method is set correctly. Then there are lots of bind's in my code... Is this the clean way for writing JS code? What is the recommended design pattern for passing methods? Maybe I should pass the entire object, or redesign my object?

Thank you.

For your reference, I pasted my code here. This is definitely not a good code. For example, probably, I may want to use multi-sql-statements rather than calling them one by one.

function insertDB(response, postData) {
  var mysql      = require('mysql');
  var async      = require('async');
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'user',
    password : 'pswd',
    database : 'mydb',
  });

  async.series([
    connection.connect.bind(connection),
    async.apply(connection.query.bind(connection),
        "CREATE TABLE IF NOT EXISTS concepts ("+
        "name VARCHAR(64) NOT NULL,"+
        "priority INT NOT NULL DEFAULT 0,"+
        "date DATE NOT NULL,"+
        "notes VARCHAR(256),"+
        "PRIMARY KEY (name))"),
    async.apply(connection.query.bind(connection),
        "INSERT INTO concepts VALUES('" +
        postData["word"] + "',0,CURDATE(),'')"),
    connection.end.bind(connection)
  ], 
  function(err, result) {
    if (err) console.error(err);
  });
}
like image 709
Joe C Avatar asked Nov 13 '22 02:11

Joe C


1 Answers

You can use call or apply to do this, both allow you to set the scope and to pass any args you want. The difference between call and apply is call takes comma seperated arguements such as:

connection.connect.call( connection, arg1, arg2, arg2 );

And apply takes an array of args like this:

var args = [ arg1, arg2, arg3 ];
connection.connect.apply( connection, args );

like image 124
kkemple Avatar answered Nov 14 '22 23:11

kkemple