How to define a Javascript function that can be bound to other Javascript libraries?

How can I define a method that can be bound to jQuery methods or other library 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;
};

Then I can bind the methods, as I want, for the Calculator object:

new Calculator(0)
    .add(1)
    .multiply(2)

But what if I would like to associate a method named "my_method" on top of the jQuery object as follows:

$(document).append("<p></p>").my_function();
$(document).my_function();

How would I define such a function? I tried adding my_function"Object" to the class, but then this does not apply to arrays of objects:

Object.my_function = function() {
     alert(this); 
     return this;
};
+4
source share
1 answer

jQuery allows you to expand your object by adding properties to jQuery.fn.

So:

$.fn.my_function = function() {
};

jQuerys , jQuery.fn.extend.

- ! , , , , , , Object; Object.prototype, .

, ( "" "" ):

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;
};
+3

All Articles