views:

307

answers:

3

How can I call a function from an object in javascript, like for example in jquery you call myDiv.html() to get the html of that div.

So what I want is this to work :

function bar(){
 return this.html();
}

alert($('#foo').bar());

this is a simplified example, so please don't say : just do $('#foo').html() :)

+5  A: 
jQuery.fn.extend({
    bar: function() {
        return this.html();
    }
});

alert($('#foo').bar());
Alex Barrett
Dang, you beat me to it. Good work. ;)
KyleFarris
+3  A: 

You mean how you call a function with an object in context?

This works-

function bar() {
    return this.html();
}

bar.apply($('#foo'));

Or if you want to attach a method to an object permanently,

obj = {x: 1};
obj.prototype.bar = function() {return this.x;};
obj.bar();
Chetan Sastry
Clean and (most important) library agnostic. +1
Pablo Fernandez
A: 
knut