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.须要扩展的属性和对象的一个对象集合。this

Student.extends(Person,{
    study: function(){
        console.log(this.name+"正在学习...");
    }
});
var can = new Student("can",21,"良好");
can.eat();
can.study();
相关文章
相关标签/搜索