1

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

3 Answers 3

9
jQuery.fn.extend({
    bar: function() {
        return this.html();
    }
});

alert($('#foo').bar());
Sign up to request clarification or add additional context in comments.

Comments

5

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

3 Comments

Clean and (most important) library agnostic. +1
However, in this context (not to abuse the word), the call method would be more apropos vs. apply.
permanently => (in the above answer) meant to mean, if you want all objects to inherit that method in it's original context, use the prototype property to assign a new method to an object.
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.