I'm new to node.js and not yet fully into scoping of anonymous functions. I declared a object with several methods. Inside my method I first get a mysql connection from mysql pool and than do a query on the connection. Now I want to call a method of my object. After reading into scoping and binding i came to the following code as result.
I was wondering whether the following is bad practise or good and if there are any better patterns to achieve this?
function myclass() {}
myclass.prototype.dosomthing = function () {}
myclass.prototype.init = function() {
pool.getConnection(function(err,connection)){
this.dosomthing();
connection.query("sql_statement", function(err,rows){
this.dosomething();
}.bind(this));
}.bind(this));
}
Thx, I really appreciate your expertise!
What you have is fine, although it does involve creating unnecessary function objects (bind creates and returns a new function).
As an alternative, just use a variable you close over:
function myclass() {}
myclass.prototype.dosomthing = function () {}
myclass.prototype.init = function() {
var self = this; // Remember `this`
pool.getConnection(function(err,connection)){
self.dosomthing(); // Use it
connection.query("sql_statement", function(err,rows){
self.dosomething(); // Use it
});
});
};
I've used self above, but generally I pick a name based on what the object actually is. So for instance, if myclass were Foo, I'd probably use the name thisFoo or similar.
Side note: The overwhelming convention in JavaScript is that functions meant to be used as constructors are named with an initial uppercase character. So MyClass rather than myclass.