1. 程式人生 > >原型物件的性質(三):更簡單的原型語法

原型物件的性質(三):更簡單的原型語法

一、重寫整個原型物件

用一個包含所有屬性和方法的物件字面量來重寫整個原型物件。

function Person(){
}
//更繁瑣的寫法
Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="SoftWare Engineer";
Person.prototype.sayName=function(){
    console.log(this.name);
};
//更簡單的寫法
Person.prototype={
    name:"Nicholas",
    age:29,
    job:
"SoftWare Engineer", sayName:function(){ console.log(this.name); } };

因為本質上重寫了預設的prototype物件,constructor屬性不再預設指向Person,而變成了普通物件的constructor值,也就是指向普通物件Object.

二、優化

function Person(){
}
Person.prototype={
    name:"Nicholas",
    age:29,
    job:"SoftWare Engineer",
    sayName:function(){
console.log(this.name); } }; var friend=new Person(); console.log(friend instanceof Object);//true console.log(friend instanceof Person);//true console.log(friend.constructor==Person);//false console.log(friend.constructor==Object);//true //修改為 function Person(){ } Person.prototype={ constructor:Person,
name:"Nicholas", age:29, job:"SoftWare Engineer", sayName:function(){ console.log(this.name); } }; var friend=new Person(); console.log(friend instanceof Object);//true console.log(friend instanceof Person);//true console.log(friend.constructor==Person);//true console.log(friend.constructor==Object);//true //以上面的方式重設constructor屬性會導致它的[[Enumerable]]特性被設定為true,而ES5中,原生的constructor屬性時不可列舉的。更優化版: function Person(){ } Person.prototype={ constructor:Person, name:"Nicholas", age:29, job:"SoftWare Engineer", sayName:function(){ console.log(this.name); } }; Object.defineProperty(Person.prototype,"constructor",{ enumerable:false, value:Person });