更简单的原型语法
function Person(){} Person.prototype.name="mike"; Person.prototype.age=29; Person.prototype.job="engineer"; Person.prototype.sayName=function(){ alert(this.name); }; function Person(){} Person.prototype={ name:"mike", age:29, job:"engineer", sayName:function(){ alert(this.name); } }; var person=new Person(); alert(person.name);
我们将Person.prototype设置为等于一个以对象字面量形式创建的新对象。结果相同,但有一个例外:constructor属性不再指向Person了。每创建一个函数,就会同时创建它的prototype对象,这个对象也会自动获得constructor属性。而第二个方法则本质上重写了默认的prototype对象,因此constructor属性也就变成了新对象的constructor属性(指向Object构造函数),不再指向Person函数。此时,尽管Instanceof操作符还能返回正确的结果,但通过constructor已经无法确定对象的类型了。
var person=new Person(); alert(person.name); alert(person instanceof Person);//true alert(person instanceof Object);//true alert(person.constructor==Person);//false alert(person.constructor==Object);//true //这里constructor属性则等于Object而不等于Person了,如果construcotr很重要,则可以设置适当的值 function Person(){} Person.prototype={ constructor:Person, name:"mike", age:29, job:"engineer", sayName:function(){ alert(this.name); };
以这种方式重设constructor属性会导致它的[[Enumerable]]特性设置为true,默认情况下,原生的constructor属性是不可枚举的。