fuction Person(name){ this.name=name; } Person.prototype={ sayName:function(){ return this.name; } }
上面代码中,Person.prototype设置为一个新对象。constructor属性不再指向Person了,而是指向了Object构造函数。
var friend=new Person();
friend.constructor==Person; //false
friend.constructor==Object;//true
改进如下,但是如下方法有一个问题,这种方式重设的constructor会导致它的[[Enumerable]]特性会变成true.默认情况下是不可枚举的。可以使用Object.defineProperty()改进。
fuction Person(name){ this.name=name; } Person.prototype={ constructor:Person, sayName:function(){ return this.name; } }
继续改进
fuction Person(name){ this.name=name; } Person.prototype={ sayName:function(){ return this.name; } } Object.defineProperty(Person.prototype,"constructor",{ enumerable:false, value:Person })