My real recommendation is not to use this or new at all (and you can use Object.create if you still want inheritance):
var SomeObject = function(config) { return { PromiseMethod1: function(){ return somePromise(config.foo); }, PromiseMethod2: function(x){ return someOtherPromise(config.bar, x); } } } var instance = SomeObject({config: true}); instance.PromiseMethod1().then(instance.PromiseMethod2);
Here I use closure and their ability to enclose variables of their parent lexical domain in my favor. Instead of relying on JavaScript to magically inject this into my function at runtime, based on which object the function is called on, because, as your problem shows, this does not always work.
However, I know that this is an unusual way of working, so if you prefer to stick with this , you will need to use bind to tell JavaScript which magical this means the function belongs to:
var SomeObject function(config) { this.config = config; } SomeObject.prototype.PromiseMethod1 = function(){ return somePromise(this.config.foo); } SomeObject.prototype.PromiseMethod1 = function(x){ return someOtherPromise(this.config.bar, x); } var instance = new SomeObject({config: true}); instance.PromiseMethod1().then(instance.PromiseMethod2.bind(instance));
In your SomeMethod example SomeMethod you are not actually using bind . You still need to bind because you pass the function to .then(f) , and the code that receives this function no longer knows which object it should use for this . Now take a look at my previously recommended code. this ses is not there, so these functions do not rely at all on the object they call on, you can pass them as functions of a higher order as much as you want, without having bind or that = this . :)
source share