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

+3


source to share


3 answers


this

inside the callback save

is in a new context and different from this

than the outside one. Store it in a variable where it has access tomethodOne



var that = this;
mongoose.save(function (err, coll) {
  //save to database
  that.methodOne();
}

      

+5


source


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

      

+2


source


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.

+2


source







All Articles