---
title: "二十六、基于包装集的插件"
author: "youyang_java"
date: "2013-05-10T14:54:59Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2013-05-10T14:54:59Z"
id: 1866759
url: "https://youyang-java.iteye.com/blog/1866759"
---

要定义基于包装集的插件，完全可以使用  
jQuery.prototype = xx  
$().xx  
在jquery不建议使用jQuery.prototype来定义包装集的插件，jquery专门定义了一个jQuery.fn = jQuery.prototype

(function($){  
    /\**  
     * 使用$.fn来创建包装集插件  
     \*/  
    $.fn.setColor = function(){  
        //此时的this对象指的是整个包装集对象，已经被封装为包装集  
        //就不用在使用$(this)来封装  
        this.css("color","#0f0");  
        //基于包装集的函数一定要能够支持链式结构  
        return this;  
    }  
     
    $.fn.formatTopic = function(options) {  
        this.each(function(n){  
            //这个时候的this就不再是包装集对象，而是这个闭包对象  
            //此时闭包对象中的引用是一个html的节点，要访问就需要使用$(this)  
            $(this).html($.fixedTopicWidth($(this).html(),options));  
        });  
    }  
})(jQuery)