任何JavaScript函数都可以用作构造函数,并且调用构造函数是需要用到一个prototype属性的,因此,每个JavaScript函数(ECMAScript5中的Function.bind()方法返回的对象除外)都自动拥有一个prototype属性,这个属性的值是一个对象,这个对象包含唯一一个不可枚举的属性constructor。
constructor
constructor的属性值是一个构造函数
var o = new Object // 或者 o = {}
o.constructor == Object //true,constructor=Object对象
var a = new Array // 或者 a = []
a.constructor == Array//true,constructor=Array对象
var n = new Number(3)
n.constructor == Number//true,constructor=Number对象
构造函数的原型中预先定义了constructor属性,对象通常继承的constructor均指代他们的构造函数。由于构造函数是类的“公共标识”,因此这个constructor属性为对象提供了类。
function Tree(name) {
this.name = name;//初始化属性
}
var theTree = new Tree("Redwood");//使用new关键字调用构造函数创建对象
console.log( "theTree.constructor is " + theTree.constructor );//运行结果如下图:
改变对象的constructor属性
function Type() { };//构造函数
var types = [
new Array,
[],
new Boolean,
true,
new Date,
new Error,
new Function,
function(){},
Math,
new Number,
1,
new Object,
{},
new RegExp,
/(?:)/,
new String,
"test"
];
for(var i = 0; i < types.length; i++) {
types[i].constructor = Type;
types[i] = [ types[i].constructor, types[i] instanceof Type, types[i].toString() ];
}; //循环遍历数组,修改数组元素中对象的constructor属性
console.log( types.join("\n") );
//输出结果如下
true, 1 和 “test” 的不受影响,因为创建他们的是只读的原生构造函数(native constructors)