定义和用法
constructor 属性返回对创建此对象的数组函数的引用。
语法
object.constructor
实例
例子 1
在本例中,我们将展示如何使用 constructor 属性:
<script type="text/javascript"> var test=new Array(); if (test.constructor==Array) { document.write("This is an Array"); } if (test.constructor==Boolean) { document.write("This is a Boolean"); } if (test.constructor==Date) { document.write("This is a Date"); } if (test.constructor==String) { document.write("This is a String"); } </script>
输出:
This is an Array
例子 2
在本例中,我们将展示如何使用 constructor 属性:
<script type="text/javascript">
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
document.write(bill.constructor);
</script>
输出:
function employee(name, jobtitle, born)
{this.name = name; this.jobtitle = job; this.born = born;}
如果alert的内容是方法或者对象的引用,会输出方法的具体内容,比如下面
<html>
<head>
</head>
<body>
<script type="text/javascript">
function a(){
var a="1";
}
alert(a);
</script>
</body>
</html>
输出:
function a(){ var a="1"; }
下面的例子演示了如何利用constructor来追踪对象最原始的构造函数:
var base = new Function();
// Or you can write: var base = function(){}
var obj = new base();
// test its parent contructor
alert(base.constructor == Function); // output true
alert(obj.constructor == base); // output true
// link into the root constructor
alert(obj.constructor.constructor == Function); // also output true
首先,创建一个新的函数实例base,易知该实例的constructor很显然指向Function类,故当测试base.constructor==Function时为真;之后有在base函数实例的基础上创建一个对象obj,由于obj是base的一个实例故obj.constructor==base亦为真;最后一句代码也返回真,这正是利用constructor形成一个链,通过它追根溯源找到了最原始了Function类。首先obj.constructor返回的是base(上面已解释不再赘述),而base又是Function类的一个实例,故obj.contructor.constructor返回的是Function类的引用。

本文详细介绍了 JavaScript 中 constructor 属性的定义与用法,并通过多个示例展示了如何使用 constructor 属性来判断对象类型及追踪对象的原始构造函数。
297

被折叠的 条评论
为什么被折叠?



