function Teacher() {this.name = 'Ms';this.age = 18;}const t = new Teacher();Teacher.prototype.car = 't1'function Student() {this.name = 'jack';this.age = 22;}Student.prototype = Teacher.prototype;Student.prototype.color = 'red'const s = new Student();console.log(s);console.log(t);
通过这种方法改变原型的指向存在问题,当我们改变student原型的时候,teacher的原型也发生改变
javascript纯面向对象开发需要使用到的一个模式,来对对象之间原型继承做中间层代理避免重复继承与代码杂乱
我们需要制造一个中间层来改变这一现状
function Teacher() {this.name = 'Jack'}Teacher.prototype.color = 'red';function Student() {this.name = 'Tom';}function Stop() {}Stop.prototype = Teacher.prototype;const stop = new Stop();Student.prototype = stop;Student.prototype.style = 'cute';const s = new Student();const t = new Teacher();console.log(s);console.log(t);
这样就可以改变 被称之
原理如下
封装圣杯模式
// 圣杯模式模块化封装let inherit = (function (){let Buffer = function (){};return function (Target,Origin) {Buffer.prototype = Origin.prototype;Target.prototype = new Buffer();Target.prototype.constructor = Target;Target.prototype.super_class= Origin;}})();function Teacher(){}Teacher.prototype.name = 'Jack';function Student(){}function Butter(){}inherit(Student,Teacher);Student.prototype.age = 19;let s= new Student();let t = new Teacher();console.log(s)console.log(t)
