inherit继承模式

                function Father () {

                }
                Father.prototype.lastName = "Zhang";
                function Son () {

                }
                Son.prototype = Father.prototype;
                
                function F () {}
                function inherit (Target, Origin) {
                    Target.prototype = Origin.prototype;
                }
                inherit(F, Father);
                Son.prototype = new F ();
                Son.prototype.name = "zhuqi";
                var son = new Son();
                var father = new Father ();

优化之后的版本:                function Father () {


                }
                Father.prototype.lastName = "Zhang";
                function Son () {

                }
                
                function inherit (Target, Origin) {
                    function F () {}
                    F.prototype = Origin.prototype;
                    Target.prototype = new F();
            Target.prototype.constuctor = Target;
} inherit(Son, Father); Son.prototype.name
= "zhuqi"; var son = new Son(); var father = new Father ();

把F当作空的构造对象,此继承模式为衍生发展下来的‘圣杯模式’。其余的继承会发生一个问题,如:给Son的prototype增加属性会连带Father一起增加。

注:inherit函数中应再加一句:Target.prototype.constuctor = Target                  因为继承的原因,Son的constructor会在Son.__proto__中找,找到的是F.__proto__,但是F.__proto__又是继承自Father,因此

Son的constructor会指向father。所以应当加一句

posted @ 2019-12-21 16:37  另一场风花雪月  阅读(216)  评论(0)    收藏  举报