从对象调用函数:object.function()

时间:2021-12-17 21:33:43

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.

如何从javascript中的对象调用函数,例如在jquery中调用myDiv.html()来获取该div的html。

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

这是一个简化的例子,所以请不要说:只做$('#foo')。html():)

3 个解决方案

#1


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

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

#2


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


To add a getHtml function to a div element with the id foo you could do this:

要将getHtml函数添加到id为foo的div元素,您可以执行以下操作:

$("#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.

如果这不是你想要的,而是扩展jQuery,你应该看看Alex Barrett的帖子。

#1


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

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

#2


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


To add a getHtml function to a div element with the id foo you could do this:

要将getHtml函数添加到id为foo的div元素,您可以执行以下操作:

$("#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.

如果这不是你想要的,而是扩展jQuery,你应该看看Alex Barrett的帖子。