Reputation: 2654
How can I define a method that can be chained to jQuery methods, or other libraries' methods ?
So let's say I have the following code:
var Calculator = function(start) {
var that = this;
this.add = function(x) {
start = start + x;
return that;
};
this.multiply = function(x) {
start = start * x;
return that;
};
I can then chain the methods as I wish to a Calculator object:
new Calculator(0)
.add(1)
.multiply(2)
But what if I'd want to chain a method named "my_method" on top of a jQuery object like so:
$(document).append("<p></p>").my_function();
$(document).my_function();
How would I define such a function ?
I tried adding my_function
to the "Object" class, but then this doesn't apply to object arrays:
Object.my_function = function() {
alert(this);
return this;
};
Upvotes: 4
Views: 198
Reputation: 224855
jQuery lets you extend its object by adding properties to jQuery.fn
.
So:
$.fn.my_function = function() {
…
};
You can also extend jQuery’s object prototype with multiple properties using jQuery.fn.extend
.
As for other libraries — it varies! If their objects have a common constructor, you can generally put your methods on their prototype, which is incidentally the problem with your Object
example; you need to put your method on Object.prototype
for it to be part of the lookup chain.
Your own example can be rewritten as this, for example (which is actually preferred for “regular” “classes”):
function Calculator(start) {
this.start = start;
}
Calculator.prototype.add = function(x) {
this.start += x;
return this;
};
Calculator.prototype.multiply = function(x) {
this.start *= x;
return this;
};
Upvotes: 3