【javascript】繼承

來源:互聯網
上載者:User

標籤:

1. js 其實是一個非物件導向的語言,通過對象的深淺複製完成繼承

 

2. 繼承方法

繼承的方法有兩種

1)prototype 原型模式

舉個例子

var Animal = function () {    this.type = ‘animal‘;    this.tmp = {name:‘hehe‘};    this.eat = function (tmp) {        console.log(‘animal eat‘);    };    this.modifyTmp = function (tmp) {        this.tmp.name = tmp;    }}var Cat = function (name) {    this.type = ‘cat‘;    this.name = name;    this.eat = function () {        console.log(‘cat eat:‘ + this.name);    }}Cat.prototype = new Animal();var cat1 = new Cat(‘cat1‘);cat1.eat();cat1.modifyTmp(‘lala‘);console.log(cat1.tmp);  // 輸出 lalavar cat2 = new Cat(‘cat2‘);cat2.eat();console.log(cat2.tmp); // 輸出lala
View Code

 

注意:此處有坑!!

為什麼通過原型繼承輸出的都是 lala 呢?

因為此時的 tmp 的類型為對象 或者 array, 當進行 prototype 繼承時, 實際是通過對象引用完成繼承,此時 cat1  cat2 都是指向同一個Animal 對象。如果tmp 為基礎類型(string,int)時,不存在引用,可以無需擔心。

可以將 tmp 重新定義給外部 cat1 cat2 對象,進行重新複製,將會指向兩個不同對象,例子如下:

var Animal = function () {    this.type = ‘animal‘;    this.tmp = {name:‘hehe‘};    this.eat = function (tmp) {        console.log(‘animal eat‘);    };    this.modifyTmp = function (tmp) {        this.tmp.name = tmp;        return this.tmp;    }}var Cat = function (name) {    this.type = ‘cat‘;    this.name = name;    this.tmp = {};    this.eat = function () {        console.log(‘cat eat:‘ + this.name);        this.tmp = this.tmp;    }}Cat.prototype = new Animal();var cat1 = new Cat(‘cat1‘);cat1.eat();cat1.tmp = cat1.modifyTmp(‘lala‘);console.log(‘cat1‘,cat1); // lalavar cat2 = new Cat(‘cat2‘);cat2.eat();cat2.tmp = cat2.modifyTmp(‘miaomiao‘);console.log(‘cat2:‘,cat2); // miaomiaoconsole.log(‘cat1‘,cat1); // lala
View Code

 

2) call apply 方式

這個是利用this 對象偷天換日。

 

【javascript】繼承

聯繫我們

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