zoukankan      html  css  js  c++  java
  • jQuery面向对象的写法

     定义的写法

    //构造函数
    function test(){
        //construct code
    }
    //初始化方法
    test.prototype.init = function(){
        //init code
    };
    //扩展方法
    test.prototype.expandFunc = function(){
        //expend function code
    };

     调用的写法

    //定义一个对象实例
    var t = new test();
    //初始化
    t.init();
    //调用扩展方法
    t.expandFunc();

    当我们new了一个新的对象实例test出来后,test内会自动带有一个constructor属性,这个属性指向构造函数本身

    alert(test.constructor);

    因为js在我们创建了一个新的对象后会自动执行这样一步操作

    test.prototype.constructor = test;

    jQuery源码的写法

    //构造函数
    function jQuery(){
        //construct code
        return new jQuery.prototype.init();
    }
    //初始化方法
    jQuery.prototype.init = function(){
        //init code
    };
    //扩展方法
    jQuery.prototype.expandFunc = function(){
        //expend function code
    };

    这样在构造函数被调用以后就会自动执行init()了。

    jQuery().expandFunc();

     但是如果只这样调用的话,init()并没有expandFunc()这个方法,所以我们改成以下调用方法:

    jQuery.prototype.init.prototype = jQuery.prototype;
    jQuery().expandFunc();

    这样就形成了一个引用的传递。

  • 相关阅读:
    10. 正则表达式匹配
    5. 最长回文子串
    板子总结
    2020: 学生查询
    解决apt-get出错
    03如何计算算法的复杂度
    ad如何从PCB中导出元件封装库
    调车遇到的问题及解决办法
    java报错与解决方法总结
    SWD下载k60
  • 原文地址:https://www.cnblogs.com/zcynine/p/5059050.html
Copyright © 2011-2022 走看看