前端学习——继承模式

    科技2024-08-19  22

    如何实现A继承B,并且再给A添加新的属性时不影响B 最完美的继承方法——圣杯模式

    <script> function inherit(Target, Origin) { //用F做中间层 function F() {}; F.prototype = Origin.prototype //new一个F,这样给son的prototype加东西不会影响到father Target.prototype = new F() Target.prototype.constructor=Target //查看到底继承自谁 Target.prototype.uber=Origin.prototype } Father.prototype.lastname = 'abc' function Father() {} function Son() {} // 先继承,再new对象 inherit(Son,Father) var son=new Son() var father=new Father() </script> <script> /* function inherit(Target, Origin) { //用F做中间层 function F() {}; F.prototype = Origin.prototype //new一个F,这样给son的prototype加东西不会影响到father Target.prototype = new F() Target.prototype.constructor=Target //查看到底继承自谁 Target.prototype.uber=Origin.prototype }*/ //另一种写法(推荐这种) var inherit=(function(){ var F=function(){}; return function(Target,Origin){ F.prototype=Origin.prototype; Target.prototype=new F() Target.prototype.constructor=Target; Target.prototype.uber=Origin.prototype } }()) Father.prototype.lastname = 'abc' function Father() {} function Son() {} // 先继承,再new对象 inherit(Son,Father) var son=new Son() var father=new Father() </script>

    Processed: 0.015, SQL: 8