Js继承之圣杯模式

圣杯模式

  • 圣杯模式的核心就是拿一个空的构造函数去当中间人,解决组合模式的缺陷。

举个例子

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

Person.prototype.say = function () {
    console.log(this.name + '----' + this.age)
}

function Student(name, age, gender, score) {
    Person.apply(this, [name, age]);
    this.gender = gender??"";
    this.score = score??"";
}

function inherit(targer, original) {
    function Fn() {};
    Fn.prototype = original.prototype;
    targer.prototype = new Fn();
    targer.prototype.constructor = targer;
};

inherit(Student, Person);

new Student('小明', 18, '男', 100).say();
posted @ 2024-09-16 22:29  HuangBingQuan  阅读(55)  评论(0)    收藏  举报