【揮舞JS】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);

子類this

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

封裝一個 extends 方法prototype

//子類  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.須要擴展的屬性和對象的一個對象集合。code

Student.extends(Person, {
    study: function () {
        console.log(this.name + '正在學習...');
    }
});

var can = new Student('can', 22, '良好');
can.eat();
can.work();
相關文章
相關標籤/搜索