zoukankan      html  css  js  c++  java
  • jquery源码基本结构和插件写法

    1. jquery源码基本结构

    (function(w){
        //工厂
        function jQuery(selector, context){
            //直接返回一个new实例,这样可以隐藏new过程,使用jQuery('#id')创建对象,而不是new jQuery('#id')
            return new jQuery.fn.init(selector, context);
        }
        //给原型提供一个简写方式,jquery.fn等于原型属性这个写法,是最经典的jquery写法
        jQuery.fn = jQuery.prototype = {
    
        };
    
        //init才是jQuery中真正的构造函数
        var init = jQuery.fn.init = function(selector, context){
    
        };
        //把构造函数的原型,替换为jQuery工厂的原型
        //这么做的目的是为了实现jQuery的插件机制,让外界可以通过jQuery方便的进行扩展
    
        //构造函数的原型 == new出来的这个实例jQuery.fn =  jQuery.prototype 这样就实现了原型继承,可以在$ 对象上面封装自己的方法。
        init.prototype = jQuery.fn;
        w.jQuery = w.$ = jQuery;
    }(window));

    2.jquery的插件写法

    jquery.fn代表jquery.prototype,可以在jquery的原型上添加方法。

    jquery.extend = jquery.fn.extend;

    jquery.extend在jquery上扩展方法,添加全局静态方法。

    jquery.fn.extend在jquery实例上扩展方法。

    2.1 jquery添加静态方法

    $.extend({
        sayHello: function(name) {
            console.log('Hello,' + (name ? name : 'aaa') + '!');
        }
    })
    
    $.sayHello('bbb'); //Hello,bbb

    2.2 jquery插件定义

    $.fn.pluginName = function(){
        //返回一个jquery对象,支持链式调用
        return this.each(function(){
            ...
        })
    }
  • 相关阅读:
    。。。
    __new__ 单例
    bokeh
    空间数据可视化
    关系网络图
    Pandas 50题练习
    seaborn
    数据输出及内容美化 简单介绍
    数据分析---项目总结
    数学建模
  • 原文地址:https://www.cnblogs.com/mengff/p/12846747.html
Copyright © 2011-2022 走看看