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