JavaScript 實作類別的多種方法執行個體

來源:互聯網
上載者:User

構造方法

複製代碼 代碼如下:function coder()
{
this.name = '現代魔法';
this.job = 'Web 開發人員';
this.coding = function ()
{ alert('我正在寫代碼'); }
}

var coder = new coder();
alert(coder.name);
coder.coding();

Factory 方法複製代碼 代碼如下:function createCoderFactory()
{
var obj = new Object();
obj.name = '現代魔法';
obj.job = '程式員';
obj.coding = function ()
{
alert('我正在寫代碼');
};
return obj;
}
var coder = createCoderFactory();
alert(coder.name);
coder.coding();

Factory 方法和構造方法都有著一個相同的缺點,就是每建立一個執行個體,都會執行個體化該類的每個函數。

原型鏈

複製代碼 代碼如下:function coder(){}
coder.prototype.name = '現代魔法';
coder.prototype.job = '程式員';
coder.prototype.coding = function(){
alert('我正在寫代碼');
};
var coder = new coder();
alert(coder.name);
coder.coding();

原型鏈有個缺點就是它所有屬性都共用,只要一個執行個體改變其他的都會跟著改變。如:

複製代碼 代碼如下:var coder1 = new coder();
var coder2 = new coder();
alert(coder1.name); /*顯示現代魔法*/
coder2.name = 'nowamagic';
alert(coder1.name); /*顯示nowamagic*/
alert(coder2.name); /*這個也顯示nowamagic*/

混合方式
以上三種都有著各自的缺點,所以我們要加以改進。

複製代碼 代碼如下:function coder()
{
this.name = '現代魔法';
this.job = '程式員';
}
coder.prototype.coding = function(){
alert('我正在寫代碼');
};

動態原鏈
要解決前三種的缺點,還有一種方法。

複製代碼 代碼如下:function coder()
{
this.name = '現代魔法';
this.job = '程式員';
if (typeof(coder._init) == 'undefined')
{
this.coding = function ()
{
alert('我正在寫代碼');
};
this._init = true;
}
}
相關文章

聯繫我們

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