0

I'm working with Javascript "classes", I have a parent "class" with a variable and a function, something like this

function WS() {
  this.auth = { client: '', password: '' };
  this.Execute = function(url, callback) {
    soap.createClient(url, function(err, client) {
      if (err) return callback(err);
      return callback(null, client);
    });
  }
}

The "subclass" uses this function and variable, like this

function Stats() {
  this.url = 'http://';

  this.emailsByDate = function(params, callback) {
    this.Execute(this.url, function(err, client) {
      if (err) return callback(err);
      client.Get(this.auth.concat(params), function(err, results) {
        if (err) return callback(err);
        return callback(results);
      });
    });
  }
}

Stats.prototype = new WS;

I'm getting through this.Execute() function, but this.auth variable is undefined, why is that

3

1 Answer 1

2

The context in which you are accessing this.auth isn't your Stats function, but instead your anonymous callback function.

You could either save the value of this.auth outside the callback function:

function Stats() {
  var auth = this.auth
  this.url = 'http://';

  this.emailsByDate = function(params, callback) {
    this.Execute(this.url, function(err, client) {
      if (err) return callback(err);
      client.Get(auth.concat(params), function(err, results) {
        if (err) return callback(err);
        return callback(results);
      });
    });
  }
}

Or you can bind the context of your callback function to that of your Stats function:

function Stats() {
  this.url = 'http://';

  this.emailsByDate = function(params, callback) {
    this.Execute(this.url, function(err, client) {
      if (err) return callback(err);
      client.Get(this.auth.concat(params), function(err, results) {
        if (err) return callback(err);
        return callback(results);
      });
    }.bind(this));
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

In addition to having the correct binding of this you might consider calling WS.call(this); in your Stats constructor.
@w1zeman1p That depends, it might be intended that the auth property is assigned to the prototype, as all the instances might want to share credentials. In that case WS.call(this) would make auth and Execute properties of each instance of Stats, and that might not be the desired effect. I think the real issue is that Execute and -- if intended -- auth should be moved to the prototype of WS, and the Stats prototype should inherit from the WS prototype using Object.create. Then the WS.call(this) call would make a lot of sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.