原型繼承、構造函數繼承、組合繼承法

原型繼承


function Person(name,sex){
    this.name=name;
    this.sex=sex;
    this.friends = {lily:'female',lucy:'female'};
    this.showFriends=function(){
        var str = ''
        for(i in this.friends){
            str+=i +' '+this.friends[i] +',';
        }
        console.log('my friends:'+str);
    }
}
Person.prototype.hello=function(){
    console.log('hello:'+this.name);
}

var per1 =  new Person('A','male');
per1.hello();
per1.showFriends();


function Student(className){
    this.class = className;
}

Student.prototype = new Person('B','male');//原型繼承將子對象的原型對象指向父對象的實例 ; 缺點:不能由子對象像父對象傳遞參數,

var stu1 = new Student(1);//不能由子對象像父對象傳遞參數,
stu1.name='C';
stu1.hello();
stu1.friends.C = 'male';//2、對於引用型的屬性修改之後會印象其他的實例對象;
stu1.showFriends();//2、對於引用型的屬性修改之後會印象其他的實例對象;

console.log("stu1 instanceof Student: ");
console.log(stu1 instanceof Student);
console.log("stu1 instanceof Person: ");
console.log(stu1 instanceof Person);

var stu2 = new Student(2);
stu2.name='D';
stu2.hello();
stu2.showFriends();//2、對於引用型的屬性修改之後會印象其他的實例對象;

console.log("stu2 instanceof Student: ");
console.log(stu2 instanceof Student);
console.log("stu2 instanceof Person: ");
console.log(stu2 instanceof Person);
缺點:1、不能由子對象像父對象傳遞參數,2、對於引用型的屬性修改之後會印象其他的實例對象;

構造函數繼承

//構造函數繼承
function Teacher(name,sex,type){
    this.type=type;
    Person.call(this,name,sex);
}

var tea1 = new Teacher('E','female','數學');
//tea1.hello(); //報錯沒有繼承到原型上的方法
tea1.friends.F = 'male';
tea1.showFriends();

var tea2 = new Teacher('G','male','語文');
tea2.friends.H = 'male';
tea2.showFriends();
console.log("tea2 instanceof Student: ")
console.log(tea2 instanceof Teacher);
console.log("tea2 instanceof Person: ")
console.log(tea2 instanceof Person);
缺點:1、不能繼承父對象原型上的方法 2、每次實例化對象會重新構建函數,浪費內存。

組合繼承法

把父對象方法掛載到父類的原型對象上去,實現方法複用
function Worker(name,sex,job){
    this.job = job;
    Person.call(this,name,sex)
}
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;//原型的構造函數指向worker

var wor1 = new Worker('I','female','程序員');
wor1.hello();
wor1.friends.J = 'male';
wor1.showFriends();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章