Reputation: 43
I ran this code into the console and tried calling:
obj.foo().bar().coo().moo();
This was my previous code:
function bar() {
this.coo = function () {
this.moo = function () {
console.log("yay");
}
}
}
obj = {
foo : function () {this.bar = bar}
};
The error that returned was "TypeError: Cannot read property 'bar' of undefined". Although, when I wrote:
obj.foo();
obj.bar();
obj.coo();
obj.moo();
It worked fine. Why didn't the first call using method chaining not work as if I was separately calling each method.
Upvotes: 1
Views: 52
Reputation: 33399
You don't return anything. You need to add return this
at the end of each of your functions in order to have an object to chain.
Upvotes: 4