定义
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》。
完