constructor属性是个很容易犯错的属性。
1.它的实质是包含在原型中的属性,而该属性是共享的,因此可以通过对象实例访问该属性。
2.当在原型对象中设置constructor属性时,只是屏蔽了原型的constructor属性,而没有覆盖
如下代码:
function Person(){
}
Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="Software Engineer";
Person.prototype.sayName=function(){
alert(this.name);
};
Person.prototype.constructor=function(){
alert("prototype");
}
var person1=new Person();
//屏蔽了原型的constructor属性
person1.constructor=function(){
alert("person1");
}
person1.name="ppp"
alert(person1.constructor); //输出function(){alert("person1");}
alert(Person.prototype.constructor); //输出function(){alert("prototype");}
alert(person1.hasOwnProperty("name")); //输出"true"
alert(person1.hasOwnProperty("constructor")); //输出"true"
alert(Person.prototype.hasOwnProperty("constructor")); //输出"true"