JS實現繼承,封裝一個extends方法


父類

function Person(name,age){
    this.name = name;
    this.age = age;
}

Person.prototype = {
    eat:function(){
        console.log(this.name+"正在吃飯...");
    },
    sang:function(){
        console.log(this.name+"正在唱歌...");
    }
}
var liuyu = new Person("劉雨", 26);

子類

function Student(name,age,score){
    Person.call(this,name,age);
    this.score = score;
}

封裝一個extends方法

//子類  extends  父類
Function.prototype.extends = function(func, options){
    for(var key in func.prototype){
        this.prototype[key] = func.prototype[key];
    }
    for(var name in options){
        this.prototype[name] = options[name];
    }
}

子類可以繼承父類的屬性和方法,也可以擴展自己的屬性和方法。extends方法參數:1.父類 2.需要擴展的屬性和對象的一個對象集合。

Student.extends(Person,{
    study: function(){
        console.log(this.name+"正在學習...");
    }
});
var can = new Student("can",21,"良好");
can.eat();
can.study();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM