首页

关于javascript中的对象容器constructor和原型链prototype图例用法说明

标签:javascript,对象容器,constructor,原型链,prototype,面向对象,js,oop     发布时间:2018-09-24   

一、前言

下图javascript的构造函数、实例对象constructor容器、prototype原型对象间三者关系

timg.jpg

下面是function方法、prototype对象、对象间三者关系

20180218162156724.jpg

二、代码示例

1. prototype原型链代码示例

<!DOCTYPE html>@b@<html> @b@<body>   @b@	<script> @b@		function objShow(){@b@			alert('方法被调用!');@b@		}@b@@b@		var myclass=Object.prototype;@b@		myclass.name='测试';@b@		myclass.id='001';@b@		//1.测试属性@b@		alert(myclass["name"]);@b@		alert(myclass.id);@b@		@b@		//2.原型链方法@b@		Object.prototype.show=objShow;@b@		myclass.show();@b@@b@		//3.isPrototypeOf测试@b@		var regObj = new RegExp();  //初始化变量。@b@		alert(RegExp.prototype.isPrototypeOf(regObj));//返回 true。@b@		@b@	 </script> @b@@b@</body>@b@</html>

2. constructor容器

<!DOCTYPE html>@b@<html> @b@<body>   @b@	<script> @b@		function objShow(){@b@			alert('方法被调用!');@b@		} @b@		@b@		var obja=new Object();@b@		//1. constructor的prototype关系@b@		obja.constructor.prototype.show=objShow; @b@		obja.show();//44 @b@		@b@		//2.string的容器@b@		x = new String("Hi");@b@		if (x.constructor == String){@b@			alert(1);@b@		}else{@b@			alert(2);@b@		}@b@		@b@		//3. fun体@b@	    function MyFunc(){@b@			   // 函数体。@b@		} @b@		y = new MyFunc;@b@		if (y.constructor == MyFunc){@b@			alert(3);@b@		}else{@b@			alert(4);@b@		}@b@			 @b@	 </script> @b@@b@</body>@b@</html>