Sunday, May 1, 2011

Call a function from an object : object.function()

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() :)

From stackoverflow
  • jQuery.fn.extend({
        bar: function() {
            return this.html();
        }
    });
    
    alert($('#foo').bar());
    
    KyleFarris : Dang, you beat me to it. Good work. ;)
  • 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();
    
    Pablo Fernandez : Clean and (most important) library agnostic. +1
  • To add a getHtml function to a div element with the id foo you could do this:

    $("#foo")[0].getHtml = function () {
      return this.innerHTML;
    };
    alert($("#foo")[0].getHtml());
    

    If this is not what you wanted, but rather extend jQuery, you should have a look at the post by Alex Barrett.

0 comments:

Post a Comment