ITPub博客

首页 > IT职业 > IT生活 > JS实现继承,封装一个extends方法

JS实现继承,封装一个extends方法

IT生活 作者:leviyang 时间:2021-09-09 09:06:13 0 删除 编辑

父类

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();

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2880/viewspace-2799447/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    77
  • 访问量
    641