定义
constructor属性返回对创建此对象的函数引用
语法
Date.constructor
//object.constructor
技术细节
| 返回值 | JavaScript 版本 |
|---|---|
| 函数对象。Date对象的函数原型。 | 1.1 |
javascript默认给函数一个属性—prototype。对,每个函数都有一个属性叫做prototype。这个prototype的属性值是一个对象(属性的集合),默认的只有一个叫做constructor的属性,指向这个函数本身。原型既然作为对象,属性的集合。不可能就只弄个constructor来玩玩!
我们现在以Person为栗子:
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.getAge = function(){
return this.age;
}
Person.prototype.getName = function(){
return this.name;
}
var p = new Person("jack",28);
console.log(p.constructor); //Person(name, age)
console.log(p.getName()); //jack
console.log(p.getAge()); //28
我们改写一下代码。
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
}
var p = new Person("jack",28);
console.log(p.constructor); //Object()
console.log(p.getAge()); //28
console.log(p.getName()); //jack
现在constructor怎么指向Object了????
因为prototype也为对象啊
其实上面代码等价于:
Person.prototype = new Object({
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
});
因为constructor始终指向创建当前对象的构造函数的引用,so上面代码p.constructor输出的是Object了。
现在想要让p.constructor输出是Person?
好吧,现在为Person.prototype.constructor赋值Person。
Person.prototype = {
constructor:Person,
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
}
ps:推荐《javascript高级程序设计3》。
完