Calling a method from another class
I have a node class:
var Classes = function () {
};
Classes.prototype.methodOne = function () {
//do something
};
when i want to call methodOne
i use this:
this. methodOne();
And it works. But for now I have to call it from another method of another class. This time it doesn't work and cannot access methodOne
:
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
this. methodOne(); //this does not work
}
how can I call the One method? I am using Classes.methodOne()
but it doesn't work
source to share
You need to create a variable outside of the mongoose function.
var self = this;
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
self.methodOne(); //If you call `this` from here, This will refer to `mongoose` class
}
If you are in an environment that works with ES6, you can use an arrow expression :
var mongoose = new Mongoose();
mongoose.save((err, col) => {
//save to database
this.methodOne();
})
source to share
What you can do is create an object of the Classes class inside your other class and refer to this method using this object: Ex:
var objClasses;
var mongoose = new Mongoose();
mongoose.save(function (err, coll) {
//save to database
objClasses = new Classes();
objClasses. methodOne(); //this should work
}
If that doesn't work, explain exactly what you want to achieve.
source to share