jquery源码学习-构造函数(2)

  最近几天一直在研究jquery源码,因为水平过低看得昏头转向。原本理解的也不是很深入,下面就用本身的想法来讲下jquery是如何定义构造函数初始化的。若是有什么不对的地方,但愿个位高手指出。css

    通常写构造函数以下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 指向改变了
相关文章
相关标签/搜索