JS學習之類的繼承

JS繼承的實現方式函數

首先聲明一個父類this

function Animal(name){ this.name =name || 'Animal'; this.sleep=function(){ console.log(this.name +'在睡覺呢~'); } } Animal.prototype.eat=function(food){ console.log(this.name+'正在吃'+food); }

1:構造函數的繼承spa

 function Dog(name){ Animal.call(this); this.name=name || 'dog'; } var dog =new Dog(); console.log(dog);

對象dog繼承了父類animal身上的屬性和方法,不過屬性相同,覆蓋了父類的屬性prototype

特色: 1 :子類共享父類的屬性和方法code

            2:能夠向父類傳遞參數對象

缺點:子類只能繼承父類的屬性和方法但並不能繼承父類的原型身上的屬性和方法blog

2:原型鏈的繼承繼承

 function Dog(name){ this.name=name || 'dog'; } Dog.prototype=new Animal(); //Dog的原型與Animal實例出來的對象指向了同一塊空間,改變任意一個值其餘的都跟着改變 var dog =new Dog(); console.log(dog);
console.log(dog.constructor); //指向了Animal
/*

        ƒ Animal(name){
           this.name =name || 'Animal';
           this.sleep=function(){
           console.log(this.name +'在睡覺呢~');
            }
         }原型鏈


*/

特色:1:父類的屬性和方法都能繼承的到,包括父類原型身上的屬性和方法也能夠繼承原型

           2:簡單,方便

缺點:1:創造子類實例時沒法向父類傳參

           2:修改子類的原型對象的值父類的實例對象也會跟着改變

           3:沒法判斷對象是子類實例化出來的仍是父類實例化出來的。

3組合繼承

 function Dog(name){ Animal.call(this); this.name=name || 'dog'; } //Dog.prototype=new Animal(); //缺點在子類實力化的過程當中父類函數執行了2次
//Dog.prototype=Animal.prototype; //缺點 Dog Animal指向了同一塊統建,當改變其中任意一個值另一個也改變
//
Dog.prototype.constructor=Dog形成Animal.prototype.constructor也成了Dog
       Dog.prototype = Object.create(Animal.prototype);  Dog.prototype.constructor=Dog; var dog=new Dog(); console.log(dog.constructor); /* ƒ Dog(name){ Animal.call(this); this.name=name || 'dog'; } */

第三種方案是目前比較完美的

相關文章
相關標籤/搜索