0

I'm writing a Javascript class with a send method which gets a promise from other class members and resolves it. The success and error functions passed to it are members of the class. It is not working as expected. The method code:

Request.prototype.send = function () {
    if (!this.promise) {
        this.promise = this.api[this.method](this.flatArgsArray, this.options);
        this.promise.then(this.distributeResults, this.distributeErrors);
    } else {
        throw new Error('This request was already answered');
    }
}

The distributeResults method fails, and the code is:

Request.prototype.distributeResults = function (result) {
    if (this.isEntityRequest) {
        var items = result.body[array_names[this.method]];
        items.forEach(this.distributeEntities);
    } else {
        this.callbacks.forEach(function (cb) {
            cb(null, result);
        });
    }
}

It fails on the this.callbacks.forEach line saying this.callbacks is undefined. But the this.isEntityRequest had to be true so I debugged and found out that everything starting with this. was undefined.

So in the send method, when I pass the methods to the promise's then, I binded the distributeResults method like this.distributeResults.bind(this) and it worked. But I'm feeling it redundant. If I have to do that I'd rather define the method as a regular JS function. I thought defining it as a method of the class would save me the binding.

So, if I defined the promise response as a class method, why do I still need to bind it? What about binding am I missing?

Pedro Otero
  • 324
  • 5
  • 15
  • Where is `this.callbacks` defined? – Nick Zuber Aug 28 '16 at 16:20
  • On a side note, are you mutating the prototype of a native `Request` object? If so _please_ don't do that - it's bad practice to mutate native objects. But if that's a custom object, carry on :) – Nick Zuber Aug 28 '16 at 16:21
  • Can you show code that is invoking `send` method? – Michał Młoźniak Aug 28 '16 at 16:27
  • *"I thought defining it as a method of the class would save me the binding."* There isn't really a concept of "methods" in JavaScript (well, in ES6 we have the method syntax, but still). "Methods" are just properties that hold functions. Functions are their own entities. They don't have strong ties to objects and *there is no autobinding*. – Felix Kling Aug 28 '16 at 16:28
  • I recommend to read [You Don't Know JS: this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&%20object%20prototypes/README.md#you-dont-know-js-this--object-prototypes) – Felix Kling Aug 28 '16 at 16:43

0 Answers0