We have some Foo object
var Foo = function() {
this.bar = function(bazinga) {
if (bazinga) {return this;}
else {return false;}
}
this.show = function() {
alert('bar');
}
};
So it allows us to do some foo.bar().bar().bar().bar();
chain.
But if in the middle of chain, bar() will return false, the next bar() attempts will cause error that undefined has no method bar()
whitch is ofc thing.
So how to make all chain return false without errors whan any of its 'rings' return false?
FIDDLE
You will have to change the return type of bar. I suggest to create a sort of null object for that purpose and add a finalization method at the end of the chain which returns false for the null object:
var Foo = function() {
var nullFoo = function() {
this.finalize = function() { return false; }
this.bar = function() { return this; }
}
this.finalize = function() { return this; }
this.bar = function(bazinga) {
if (bazinga) {return this;}
else {return new nullFoo();}
}
this.show = function() {
alert('bar');
}
};
foo.bar().bar().bar().bar().finalize();
For your fiddle example I did not use the finalize method but instead gave the null object a show method. Otherwise you still would have false.show()
at the end:
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With