1 var person = function(name){ 2 this.name = name 3 }; 4 person.prototype.getName=function(){//經過person.prototype設置函數對象屬性 5 return this.name; 6 } 7 var crazy= new person(‘crazyLee’); 8 crazy.getName(); //crazyLee//crazy繼承上屬性
在函數內建立一個對象,給對象賦予屬性及方法再將對象返回設計模式
1 function Person() { 2 var People = new Object(); 3 People.name = 'CrazyLee'; 4 People.age = '25'; 5 People.sex = function(){ 6 return 'boy'; 7 }; 8 return People; 9 } 10 11 var a = Person(); 12 console.log(a.name);//CrazyLee 13 console.log(a.sex());//boy
無需在函數內部從新建立對象,而是用this指代數組
1 function Person() { 2 this.name = 'CrazyLee'; 3 this.age = '25'; 4 this.sex = function(){ 5 return 'boy' 6 }; 7 8 } 9 10 var a = new Person(); 11 console.log(a.name);//CrazyLee 12 console.log(a.sex());//boy
函數中不對屬性進行定義,利用prototype屬性對屬性進行定義,能夠讓全部對象實例共享它所包含的屬性及方法。函數
function Parent() { Parent.prototype.name = 'carzy'; Parent.prototype.age = '24'; Parent.prototype.sex = function() { var s="女"; console.log(s); } } var x =new Parent(); console.log(x.name); //crazy console.log(x.sex()); //女
原型模式+構造函數模式。這種模式中,構造函數模式用於定義實例屬性,而原型模式用於定義方法和共享屬性this
1 function Parent(){ 2 this.name="CrazyLee"; 3 this.age=24; 4 }; 5 Parent.prototype.sayname=function(){ 6 return this.name; 7 }; 8 9 var x =new Parent(); 10 console.log(x.sayname()); //Crazy
將全部信息封裝在了構造函數中,而經過構造函數中初始化原型,這個能夠經過判斷該方法是否有效而選擇是否須要初始化原型。spa
1 function Parent(){ 2 this.name="CrazyLee"; 3 this.age=24; 4 if(typeof Parent._sayname=="undefined"){ 5 Parent.prototype.sayname=function(){ 6 return this.name; 7 } 8 Parent._sayname=true; 9 } 10 }; 11 12 var x =new Parent(); 13 console.log(x.sayname());