標籤:style blog color io ar cti div 工作
最近幾天一直在研究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 指向改變了