JS原型链的案例

217 阅读1分钟

1.问题:

    <script type="text/javascript">
			function Parent(){
				this.a=1;
				this.b=[1,2,this.a];
				this.c={
					demo:5
				};
				this.show=function(){
					console.log(this.a,this.b,this.c.demo);//1,[1,2,1],5
				}
			}
			function Child(){
				this.a=2;
				this.change=function(){
					this.b.push(this.a);
					this.a=this.b.length;
					this.c.demo=this.a++;
				}
			}
			Child.prototype=new Parent();
			//Child.prototype={__proto__:Parent.prototype,a:1,b:[1,2,1],c:{demo:5},show:fun}
			var parent=new Parent();//parent={__proto__:Parent.prototype,a:1,b:[1,2,1],c:{demo:5},show:fun}
			var child1=new Child();//child1={__proto__:Child.prototype,a:2,change:fun}
			var child2=new Child();//child2={__proto__:Child.prototype,a:2,change:fun}
			child1.a=11;//child1={__proto__:Child.prototype,a:11,change:fun}
			child2.a=12;//child2={__proto__:Child.prototype,a:12,change:fun}
			parent.show();//parent={__proto__:Parent.prototype,a:1,b:[1,2,1],c:{demo:5},show:fun}==>1,[1,2,1],5
			child1.show();//child1={__proto__:Child.prototype,a:11,change:fun}==>11,[1,2,1],5
			child2.show();//12,[1,2,1],5
			child1.change();//child1={__proto__:{__proto__:Parent.prototype,a:1,b:[1,2,1,11],c:{demo:4},show:fun},a:5,change:fun}
			child2.change();//child2={__proto__:{__proto__:Parent.prototype,a:1,b:[1,2,1,11,12],c:{demo:5},show:fun},a:6,change:fun}
			parent.show();//1,[1,2,1],5
			//child1和child2共用一个原型对象
			child1.show();//5,[1,2,1,11,12],5
			child2.show();//6,[1,2,1,,11,12],5
		</script>

答案:

image.png

难点在于引用数据的引用以及原型链的知识点,还有函数的运行

比如:Child的原型对象和parent的数据一样,但是它们不是同一个引用数据。 函数只有调用了,代码才会运行。