zoukankan      html  css  js  c++  java
  • jquery源码学习-构造函数(2)

      最近几天一直在研究jquery源码,由于水平太低看得昏头转向。本来理解的也不是很深刻,下面就用自己的想法来说下jquery是如何定义构造函数初始化的。如果有什么不对的地方,希望个位高手指出。

        一般写构造函数如下

    function Aaa(){}
    Aaa.prototype.init = function(){};
    Aaa.prototype.css = function(){};
    
    var a1 = new Aaa();
    a1.init(); //初始化
    a1.css();

      jQuery写法如下

    function jQuery(){
        return new jQuery.prototype.init(); // =>jQuery.prototype
    };
    jQuery.prototype = {
    constructor : jQuery, init :
    function(/*初始化工作*/){}, css : function(){} } jQuery.prototype.init.prototype = jQuery.prototype; jQuery().css();
    jQuery() -> new jQuery.prototype.init();  
    jQuery.prototype.init.prototype = jQuery.prototype;
    把jQuery的原型指向了,自己的init方法(看作构造函数)的原型上。 (不知道怎么说,反正是这个意思,希望高手指出。)

    注:这里加上 constructor 属性主要起到修正作用。
    示例
    function Aaa(){}
    
    var a1 = new Aaa();
    //构造函数本身, 自动生成 Aaa.prototype.constructor = Aaa;
    alert(a1.constructor);  //Aaa
    
    //在Aaa原型上加2个属性
    Aaa.prototype.name = 'hello';
    Aaa.prototype.age = 30;
    alert(a1.constructor);  //还是Aaa,不会变化 
    
    //如果重构了Aaa的原型,即覆盖
    Aaa.prototype = {  
      //constructor : Aaa, //修正指向
      name: 'hello',
      age : 30
    };
    
    var a1 = new Aaa();
    alert(a1.constructor);  //如果不加constructor : Aaa 指向改变了
  • 相关阅读:
    sql
    字符和字符串处理例子
    如何用火狐设置代理
    数组指针的一个小例子
    (转)数组指针和指针数组的区别
    函数
    (转)C语言指针5分钟教程
    通俗版解释网关,IP地址,ARP欺骗,DDOS攻击
    计算网络地址
    计算机网络性能指标
  • 原文地址:https://www.cnblogs.com/loveyouyou616/p/3916435.html
Copyright © 2011-2022 走看看