-
原型規則
- 原型規則
-
- 所有的參考型別(陣列、物件、函式),都具有物件特征,即可自由擴展屬性;
- 所有的參考型別,都有一個_proto_ 屬性(隱式原型),屬性值是一個普通物件;
- 所有函式,都具有一個prototype(顯示原型),屬性值也是一個普通原型;
- 所有的參考型別(陣列、物件、函式),其隱式原型指向其建構式的顯式原型;(obj.proto === Object.prototype);
- 當試圖得到一個物件的某個屬性時,如果這個物件本身沒有這個屬性,那么會去它的_proto_(即它的建構式的prototype)中去尋找;
- 原型物件:prototype 在js中,函式物件其中一個屬性:原型物件prototype,普通物件沒有prototype屬性,但有_proto_屬性, 原型的作用就是給這個類的每一個物件都添加一個統一的方法,在原型中定義的方法和屬性都是被所以實體物件所共享,
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繼承上屬性
- 原型鏈 ?當試圖得到一個物件f的某個屬性時,如果這個物件本身沒有這個屬性,那么會去它的_proto_(即它的建構式的prototype)obj._proto_中去尋找;當obj._proto也沒有時,便會在obj._proto.proto(即obj的建構式的prototype的建構式的prototype)中尋找;
-
設計模式
- 工廠模式
在函式內創建一個物件,給物件賦予屬性及方法再將物件回傳
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()); //女
- 混合模式
原型模式+建構式模式,這種模式中,建構式模式用于定義實體屬性,而原型模式用于定義方法和共享屬性
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
- 動態原型模式
將所有資訊封裝在了建構式中,而通過建構式中初始化原型,這個可以通過判斷該方法是否有效而選擇是否需要初始化原型,
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());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/174706.html
標籤:JavaScript
