JS的建構函式

來源:互聯網
上載者:User

標籤:src   代碼   tar   not   關鍵字   span   blank   多次   建構函式   

//建構函式//使自己的對象多次複製,同時執行個體根據設定的訪問等級可以訪問其內部的屬性和方法//當對象被執行個體化後,建構函式會立即執行它所包含的任何代碼function myObject(msg){//特權屬性(公有屬性)this.myMsg = msg; //只在被執行個體化後的執行個體中可調用this.address = ‘上海‘;//私人屬性var name = ‘豪情‘;var age = 29;var that = this;//私人方法function sayName(){alert(that.name);}//特權方法(公有方法)//能被外部公開訪問//這個方法每次執行個體化都要重新構造而prototype是原型共用,所有執行個體化後,都共同引用同一個this.sayAge = function(){alert(name); //在公有方法中可以訪問私人成員}//私人和特權成員在函數的內部,在建構函式建立的每個執行個體中都會包含同樣的私人和特權成員的副本,//因而執行個體越多佔用的記憶體越多}//公有方法//適用於通過new關鍵字執行個體化的該對象的每個執行個體//向prototype中新增成員將會把新方法添加到建構函式的底層中去myObject.prototype.sayHello = function(){alert(‘hello everyone!‘);}//靜態屬性//適用於對象的特殊執行個體,就是作為Function對象執行個體的建構函式本身myObject.name = ‘china‘;//靜態方法myObject.alertname = function(){alert(this.name);}//執行個體化var m1 = new myObject(‘111‘);//---- 測試屬性 ----////console.log(myObject.name); //china//console.log(m1.name); //undefined, 靜態屬性不適用於一般執行個體//console.log(m1.constructor.name); //china, 想訪問類的靜態屬性,先訪問該執行個體的建構函式,然後在訪問該類靜態屬性//console.log(myObject.address); //undefined, myObject中的this指的不是函數本身,而是調用address的對象,而且只能是對象//console.log(m1.address); //上海 此時this指的是執行個體化後的m1//---- 測試方法 ----////myObject.alertname(); //china,直接調用函數的類方法//m1.alertname(); //FF: m1.alertname is not a function, alertname 是myObject類的方法,和執行個體對象沒有直接關係//m1.constructor.alertname(); //china, 調用該物件建構函數(類函數)的方法(函數)//m1.sayHello(); //hello everyone, myObject類的prototype原型下的方法將會被執行個體繼承//myObject.sayHello(); //myObject.sayHello is not a function,sayHello是原型方法,不是類的方法//---- 測試prototype ----////console.log(m1.prototype); //undefined, 執行個體對象沒有prototype//console.log(myObject.prototype); //Object //alert(myObject.prototype.constructor); //console.log返回myObject(msg),此時alert()更清楚,相當於myObject//console.log(myObject.prototype.constructor.name); //china, 相當於myObject.name;

 

 

 

參考:

http://www.cnblogs.com/mrsunny/archive/2011/05/09/2041185.htmlhttp://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.html

 

近年來發現有人對做瞭解釋,分享:

http://www.cnblogs.com/daishuguang/p/3978409.htmlhttp://www.cnblogs.com/wangfupeng1988/p/3979985.htmlhttp://anykoro.sinaapp.com/2012/01/31/javascript%E4%B8%ADfunctionobjectprototypes__proto__%E7%AD%89%E6%A6%82%E5%BF%B5%E8%AF%A6%E8%A7%A3/  

JS的建構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.