jquery源碼學習-建構函式(2)

來源:互聯網
上載者:User

標籤: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 指向改變了

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.