The constructor property is a reference to the function that created an object.
constructor属性为所建立对象的函数参考。
constructor 属性是所有具有 prototype 的对象的成员。它们包括除 Global 和 Math 对象以外的所有 JScript内部对象。constructor 属性保存了对构造特定对象实例的函数的引用
可以理解JAVA里面的构造方法,如下:
构造方法:
<script language="javascript">
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var zhangsan = new Student("zhangsan",18,"male");
alert(zhangsan.name)
alert(zhangsan.age)
alert(zhangsan.sex)
alert(zhangsan.constructor)
</script>
输出内容为:
zhangsan
18
male
function Student(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
即alert(zhangsan.constructor)返回的内容为Student函数体。
可以利用constructor属性来判断对象的类型
如下:
var newDate = new Date();
if(newDate.constructor == Array){
alert('this is a array')
}else if(newDate.constructor == Date){
alert("this is a Date')
}else{
}
输出内容为:this is a Date
x = new String("Hi"); if (x.constructor == String) // 进行处理(条件为真)。 或 function MyFunc { // 函数体。 } y = new MyFunc; if (y.constructor == MyFunc) // 进行处理(条件为真)。