简体   繁体   中英

Class construction in node.js using this

im new to node and js

i have a utilities class that is build like this and can be initiated by Utilities.newObject and then used as this Utilities.someMethod(args, callback):

exports.newObject = function(){
  return new Utilities();
}

var Utilities = function(){

  this.method1 = function(args, callback){
    //
  }

  this.method2 = function(args, callback){
    //stuff
  }

  this.method3 = function(args, callback){
    //stuff
  }
}

My problem: is there a way to use method1 in method 2? This works as i call this directly in the method, but doesn't if its called in a function, running in a method:

exports.newObject = function(){
  return new Utilities();
}

var Utilities = function(){

  this.method1 = function(args, callback){
    someCallbackFunction(args, function(result){
      this.method2(args) // THIS DOES NOT WORK
    });
  }

  this.method2 = function(args, callback){
    this.method1(args) // THIS  WORKS
  }

  this.method3 = function(args, callback){
    //stuff
  }
}

Any advice for a novice?

try this out:

exports.newObject = function(){
    return new Utilities();
}

var Utilities = function(){
    this.method1 = function(args, callback){
        var self = this;
        someCallbackFunction(args,function(){       
            self.method2(args,function(){
            });
        });  
    }

   this.method2 = function(args, callback){
       this.method1();   
    }

   this.method3 = function(args, callback){
       //stuff
    }
}

Since your functions are all static you can just directly export a map of them

var utilities = {
    method1: function() {
        someCallbackFunction(args, function(result){
            utilities.method2(args)
        });
    },

    method2: function() {

    },

    method3: function() {

    }
};

module.exports = utilities;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM