The difference between JQuery and JQuery.fn

 

原文链接: http://stackoverflow.com/questions/2845981/jquery-difference-between-functionname-and-fn-functionname

 

 

I'm sure this question has been asked several times before, but I can't find the link.

$.fn points to the jQuery.prototype. Any methods or properties you add to it become available to all instance of the jQuery wrapped objects.

$.something adds a property or function to the jQuery object itself.

Use the first form $.fn.something when you're dealing with DOM elements on the page, and your plugin does something to the elements. When the plugin has nothing to do with the DOM elements, use the other form $.something.

For example, if you had a logger function, it doesn't make much sense to use it with DOM elements as in:

$("p > span").log();

For this case, you'd simply add the log method to the jQuery object iself:

jQuery.log = function(message) {
   
// log somewhere
};

$
.log("much better");

However, when dealing with elements, you would want to use the other form. For example, if you had a graphing plugin (plotGraph) that takes data from a <table> and generates a graph - you would use the $.fn.* form.

$.fn.plotGraph = function() {
   
// read the table data and generate a graph
};

$
("#someTable").plotGraph();

On a related note, suppose you had a plugin which could be used either with elements or standalone, and you want to access it as $.myPlugin or $("<selector>").myPlugin(), you can reuse the same function for both.

Say we want a custom alert where the date is prepended to each alert message. When used as a standalone function, we pass it the message as an argument, and when used with elements, it uses thetext of the element as the message:

(function() {
   
function myAlert(message) {
        alert
(new Date().toUTCString() + " - " + message);
   
}

    $
.myAlert = myAlert;

    $
.fn.myAlert = function() {
       
return this.each(function() {
            myAlert
($(this).text());
       
});
   
};
})();

It's wrapped in a self-executing function so myAlert doesn't spill out to the global scope. This is an example or reusing functionality between both the plugin forms.

As theIV mentioned, it is a good practice to return the jQuery wrapped element itself since you wouldn't want to break chaining.

 

总结如下:

1. JQuery的继承是对于对象本身的拓展, 不影响其他的实例.  fn则会影响所有的实例,是对prototype的拓展。

2.  JQuery的拓展只是针对功能,与DOM没有关系的功能。 fn需要与DOM的element有关系。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值