最近幾天一直在研究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 指向改變了