Javascript Method Chain

I am trying to find a way to combine these methods together similarly to jQuery. here is an example of what i mean:

(function() { window.foo = function foo( id ) { if( window == this ) return new foo( document.getElementById( id ) ); this.alert = function() { alert( object.value ); } } }()); foo('input').alert(); 

So, as you can see, I would like to use the object that was passed to the class as part of the warning function, but I do not want to store it in the class via this.object = id , and then do alert( this.object.value );

What would be an elegant way to do this?

+4
source share
2 answers

jQuery is only chaining, returning the same jQuery object from many of its methods. Your method does not always return a value, so it will not connect reliably. If you always return a value of the same type, the chain may start to make sense.

 window.foo = function foo( id ) { if( window === this ) return new foo( document.getElementById( id ) ); this.alert = function() { if (this.value) alert( this.value ); } return this; } foo('input').alert(); 
+4
source

You do not need to save the link in the object, because you already have it as id .

 this.alert = function() { alert(id.value); return this; } 
-1
source

All Articles