JavaScript 构造器(constructor)介绍

JavaScript构造器(constructor)是对象的一个属性,为只读 ,主要用途有:

1、可以用来判断某对象是否由某个函数(类)实例化得来;

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>constructor</title>
</head>

<body>

<script lang="javascript">
	
	var ClassA = function(){
 		this.name = "Zhangsan";
 		var age = 40;
	}
 
	
	ClassA.prototype.url = "http://localhost:9080/myweb";
 
	
	var obj = new ClassA();
	obj.url = "http://www.baidu.com";
	obj.name = "Lisi";
	
	if(obj.constructor == ClassA){
		alert('Object obj2 initialized by  ClassA!');
	}
	
</script>
</body>

</html>


2、获取对象的构造函数,可以重复利用其来实例化同类的对象:

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>constructor</title>
</head>

<body>

<script lang="javascript">
	
	var ClassA = function(){
 		this.name = "Zhangsan";
 		var age = 40;
	}
 
	
	ClassA.prototype.url = "http://localhost:9080/myweb";
 
	
	var obj = new ClassA();
	obj.url = "http://www.baidu.com";
	

	obj.name = "Lisi";
	
	alert('obj.url:' + obj.url + ',prototype.url:' + ClassA.prototype.url + ',name:' + obj.name + ',age:' + obj.age
		+ ',constructor :' + obj.constructor );
		
	var obj2 = new obj.constructor();
	alert(obj2.name);	
	
</script>
</body>

</html>


posted @ 2017-07-25 19:56  hongweigg  阅读(57)  评论(0编辑  收藏  举报