JavaScript 圣杯模式笔记
作者:互联网
<!-- <script>
//extend inherit(Target,Origin)
//inherit使用
Father.prototype.lastName = 'He'; function Father() {} function Son() {} function inherit(Target, Origin) { Target.prototype = Origin.prototype; } inherit(Son, Father); var son = new Son(); //inherit不足,Son和Father的原型指向的同一个,当Son原型改动时Father也会变化 </script> -->
<script> //圣杯模式 Father.prototype.lastName = 'He'; function Father() {} function Son() {} //常用写法 // function inherit(Target, Origin) { // function F() {} // F.prototype = Origin.prototype; // Target.prototype = new F(); // Target.prototype.constuctor = Target; // Target.prototype.uber = Origin.prototype; // } //这种圣杯模式的本质在于,中间生成了一个对象,起到了隔离的作用,今后为Son.prototype添加属性时,全部都会加在这个对象里面,所以不会对父级产生影响。而向上查找是沿着__proto__查找,可以顺利查找到父级的属性,实现继承。
//利用闭包将F作为一个私有化变量写法 var inherit = (function () { var F = function () {}; return function (Target, Origin) { F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; //真正继承自Origin }; })();
inherit(Son, Father); Son.prototype.name = 'jun'; var son = new Son(); var father = new Father(); </script>
Father.prototype.lastName = 'He'; function Father() {} function Son() {} function inherit(Target, Origin) { Target.prototype = Origin.prototype; } inherit(Son, Father); var son = new Son(); //inherit不足,Son和Father的原型指向的同一个,当Son原型改动时Father也会变化 </script> -->
<script> //圣杯模式 Father.prototype.lastName = 'He'; function Father() {} function Son() {} //常用写法 // function inherit(Target, Origin) { // function F() {} // F.prototype = Origin.prototype; // Target.prototype = new F(); // Target.prototype.constuctor = Target; // Target.prototype.uber = Origin.prototype; // } //这种圣杯模式的本质在于,中间生成了一个对象,起到了隔离的作用,今后为Son.prototype添加属性时,全部都会加在这个对象里面,所以不会对父级产生影响。而向上查找是沿着__proto__查找,可以顺利查找到父级的属性,实现继承。
//利用闭包将F作为一个私有化变量写法 var inherit = (function () { var F = function () {}; return function (Target, Origin) { F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; //真正继承自Origin }; })();
inherit(Son, Father); Son.prototype.name = 'jun'; var son = new Son(); var father = new Father(); </script>
标签:function,Origin,圣杯,Target,JavaScript,Father,笔记,Son,prototype 来源: https://www.cnblogs.com/ilovejun/p/14093026.html