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.
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.
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.