继承(2)-圣杯模式

4.所以就引出了最后一种模式————圣杯模式。

方法还是公有原型。

               Father.prototype

               function F(){}

               F.prototype = Father.prototype

               Son.prototype = new F();

这个Father.prototype是两方的原型,F充当了一个中间层,F.prototype = Father.prototype,他俩·共用一个原型,然后son和F要形成一个关系,通过原型链的方式形成关系,现在son的原型等于new F,

New的f可以通过原型链的方式找到Father.prototype,这也就形成了继承,son依然可以继承Father.prototype,现在有个好处就是son想给自己的prototype加东西,不会影响Father.prototype,因为son的原型是new F,new F的原型才是Father.prototype,这是两层关系,所以咱把这种东西提取出来,提取出一个公式出来,封装到一个函数里面,再次实现a继承b。

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

这就实现了最终的继承。

原型上都有一个系统给咱们自带的属性叫Constructor,constructor默认的值是不是指向他的构造函数,现在son的constructor理应是什么?理应是出现Son是吧,但是现在

他是father,怎么来的?

现在son的原型是谁,是new F()吧,new F()身上有constructor吗,对象身上都没有吧,他是原型身上的,那现在再往上找,new F()的原型是谁,是father.prototype吧,father.prototype上面有没有constructor,必须有啊,指的是father,所以son要访问constructor的时候要指向father吧,指向紊乱了是吧,所以现在想把son的constructor归位。

function inherit(Target,Origin){
				function F(){};
				F.prototype = origin.prototype;
				Target.prototype = new F();
				Target.prototype.constructor = Target;
			}

是不是这样就完事了,

function inherit(Target,Origin){
				function F(){};
				F.prototype = origin.prototype;
				Target.prototype = new F();
				Target.prototype.constructor = Target;
			}
			Father.prototype.lastName = "deng";
			function Father(){
			}
			function Son (){
			}
			inherit(Son,Father);
			var son = new Son();
			var father = new Father();

现在有一个小问题:我把第三四行换个位置,还好使吗?

function inherit(Target,Origin){
				function F(){};
				F.prototype = origin.prototype;
				Target.prototype = new F();
				Target.prototype.constructor = Target;
			}

是不是不好使了,还是原型指向的问题吧,new的时候是用的原来的原型,你后给人改了,已经晚了,人家已经new完了是吧,所以一定得在new之前改原型。

下节课来讲一下一种高大上的写法。

猜你喜欢

转载自blog.csdn.net/hdq1745/article/details/83048879