常建57

路漫漫其修远兮。。。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

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
})

 

posted on 2017-03-01 22:42  常建57  阅读(272)  评论(0编辑  收藏  举报