javascript:inheritance(1)

來源:互聯網
上載者:User

偽類

//構造器調用模式
var Mammal = function (name)
{
this.name = name;
};
Mammal.prototype.get_name = function()
{
return this.name;
};
Mammal.prototype.says = function ()
{
return this.saying || '';
};
var Cat = function(name)
{
this.name = name;
this.saying = 'meow';
};
Cat.prototype = new Mammal();
Cat.prototype.purr = function(n){
var i, s = '';
for(i = 0; i < n; i ++)
{
if(s)
{
s += '-';
}
s += 'r';
}
return s;
};
Cat.prototype.get_name = function()
{
return this.says() + ' ' + this.name + ' ' + this.says();
};

var myCat = new Cat('Henrietta');
var says = myCat.says();
var purr = myCat.purr(5);
var name = myCat.get_name();

//上面的偽類模式看起來很奇怪,我們可以隱藏一些醜陋的細節。
//使用method方法定義一個inherits方法來實現

Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Function.method('inherits', function(Parent){
this.prototype = new Parent();
return this;
});
var Cat = function(name)
{
this.name = name;
this.saying = 'meow';
}.inherits(Mammal).method('purr',function(n){
var i, s = '';
for(i = 0; i < n; i ++)
{
if(s)
{
s += '-';
}
s += 'r';
}
return s;
}).method('get_name', function(){
return this.says() + ' ' + this.name + ' ' + this.says();
});

//以上代碼有類似於“類”的構造器函數,但是它沒有私人環境,所有屬性都是公開的。無法訪問父類的方法。
//而且如果調用的時候沒有用new,那麼this將被綁定到全域對象上,所以不但沒有擴充新對象,反而破壞了全域變數。

相關文章

聯繫我們

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