How to implement chained method calls like jQuery?
You are almost there:
new foo('hello').alertTest('world');
or if you don't like the new
:
var bar = function bar(str) {
this.str = str;
};
bar.prototype = {
alertTest : function(additional){
alert(this.str + ' ' + additional);
return this;
}
};
function foo(str) {
return new bar(str);
}
foo('hello').alertTest('world');
Live Demo.
I did something like this a while ago and it was a ton of fun to create!
If i remember correctly, To be able to use dot-operators, I had to return the object as part of the original function call. This way I could chain lots of stuff together like $(id).value('asdf').color('#ff0000')
function $(id){
this.e = document.getelementbyid(id)
me = this
this.val = function (newval) {
this.e.value = newval;
return me; // <- Important
};
return this; // <- Important
}
$("textbox1").val("New Value") // changes textbox1's value to "New Value"
If it helps for reference: http://www.mikedoesweb.com/vis/