標籤:
接著上次的進度,開始看第6章。
第6章 物件導向的程式設計
理解對象
建立自訂對象最簡單的方式就是建立一個 Object 的執行個體,然後為它添加屬性和方法。
var person = new Object();person.name = ‘xxx‘;person.say = function(){alert(this.name);}//等同於 對象字面量var person = {name: ‘xxx‘,say: function(){alert(this.name);}}
ECMAScript中有兩種屬性:資料屬性 訪問器屬性
資料屬性包含一個資料值的位置,在這個位置可以讀寫。要修改屬性預設的特性,必須使用 ECMAScript 5定義的 Object.defineProperty() 方法。這個方法接收3個參數:屬性所在的對象、屬性的名稱、一個描述符對象(configurable、enumerable、writable、value).
var person = {};Object.defineProperty(person, "name", { writable: false, value: "Nicholas"});alert(person.name); //Nicholasperson.name = "Michael";alert(person.name); //Nicholas//Object.defineProperty(person, "name", { configurable: false, value: "Nicholas"});
訪問器屬性不包含資料值,包含一對 getter setter。訪問器屬性不能直接定義,必須使用 defineProperty() 來定義。
讀取屬性的特性
ECMAScript 5中的 getOwnPropertyDescriptor() 方法可以取得屬性的描述符。這個方法接收2個參數:屬性所在的對象、要讀取描述符的屬性名稱。
建立對象
雖然 Object 建構函式或對象字面量都可以建立單個對象,但這些方式有缺點:使用同一個介面建立很多個物件,會產生大量的重複代碼。
1. 原廠模式
//原廠模式function createPerson(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o;}var person1 = createPerson("Nicholas", 29, "Software Engineer");var person2 = createPerson("Greg", 27, "Doctor");person1.sayName(); //"Nicholas"person2.sayName(); //"Greg"
2. 建構函式模式
//建構函式模式function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); }; }var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");person1.sayName(); //"Nicholas"person2.sayName(); //"Greg"
建構函式都應該以一個大寫字母開頭、非建構函式應該以一個小寫字母開頭。
要建立一個新執行個體,必須使用 new 操作符。
一般經曆4個步驟:
1). 建立一個新對象
2). 將建構函式的範圍賦給新對象(這時this指向了這個新對象)
3). 執行建構函式中的代碼(為新對象添加屬性、方法)
4). 返回新對象
建立的新對象都有一個 constructor (建構函式)屬性,這個屬性指向 那個new執行個體的建構函式。
instanceof 操作符用來檢測物件類型。
//constructoralert(person1.constructor == Person); //truealert(person2.constructor == Person); //true//instanceofalert(person1 instanceof Object); //truealert(person1 instanceof Person); //truealert(person2 instanceof Object); //truealert(person2 instanceof Person); //true
建構函式也是普通的函數, 任何函數通過new操作符調用,那它就可以作為建構函式。
//new操作符 當作建構函式調用var person = new Person("Nicholas", 29, "Software Engineer");person.sayName(); //"Nicholas"//作為普通函數調用Person("Greg", 27, "Doctor"); //adds to windowwindow.sayName(); //"Greg"//在另一個對象範圍調用var o = new Object();Person.call(o, "Kristen", 25, "Nurse");o.sayName();
3. 原型模式
新建立的每個函數都有一個 prototype(原型) 屬性,這個屬性是一個指標,指向一個對象,這個對象的用途是包含可以有特定類型的所有執行個體共用的屬性和方法。
//原型模式function Person(){}Person.prototype.name = "Nicholas";Person.prototype.age = 29;Person.prototype.job = "Software Engineer";Person.prototype.sayName = function(){ alert(this.name);};var person1 = new Person();person1.sayName(); //"Nicholas"var person2 = new Person();person2.sayName(); //"Nicholas"alert(person1.sayName == person2.sayName); //true
理解原型對象
無論什麼時候,只要建立一個新函數,就會根據一組特定的規則為該函數建立一個 prototype 屬性,這個屬性指向函數的原型對象。 在預設情況下,所有原型對象都會自動獲得一個 constructor 屬性,這個屬性包含一個指向 prototype 屬性所在函數的指標。
建立了自訂建構函式後,其原型對象預設只會取得 constructor 屬性;其他方法,則是從 Object 繼承而來。 當調用建構函式建立一個新執行個體,該執行個體的內部將包含一個指標(內部屬性[[prototype]])指向建構函式的原型對象。( 在一些瀏覽器中這個屬性為 __proto__ )
Person的執行個體:person1, person2,這2個執行個體都包含一個內部屬性( 某些瀏覽器中:__proto__ ),這個屬性指向了 Person.prototype。( 換句話說這個內部屬性和建構函式沒有直接關係 )
可以通過 isPrototypeOf() 方法來確定對象之間是否存在這種關係(執行個體內部屬性[[prototype]]指向建構函式原型)
alert(Person.prototype.isPrototypeOf(person1)); //truealert(Person.prototype.isPrototypeOf(person2)); //true
使用 hasOwnProperty() 方法可以檢測一個屬性是存在於執行個體中,還是存在於原型中。
//檢測屬性function Person(){} Person.prototype.name = "Nicholas";Person.prototype.age = 29;Person.prototype.job = "Software Engineer";Person.prototype.sayName = function(){ alert(this.name);};var person1 = new Person();var person2 = new Person();alert(person1.hasOwnProperty("name")); //falsealert("name" in person1); //trueperson1.name = "Greg";alert(person1.name); //"Greg" – from instancealert(person1.hasOwnProperty("name")); //truealert("name" in person1); //truealert(person2.name); //"Nicholas" – from prototypealert(person2.hasOwnProperty("name")); //falsealert("name" in person2); //truedelete person1.name;alert(person1.name); //"Nicholas" - from the prototypealert(person1.hasOwnProperty("name")); //falsealert("name" in person1); //true
//判斷原型屬性function hasPrototypeProperty(object, name){ return !object.hasOwnProperty(name) && (name in object);}var person = new Person(); alert(hasPrototypeProperty(person, "name")); //trueperson.name = "Greg";alert(hasPrototypeProperty(person, "name")); //false
在使用for-in迴圈時,返回是所有能夠通過對象訪問的、可枚舉的屬性,包括執行個體的屬性,原型的屬性。要取得對象所有可枚舉的執行個體屬性,可以使用 ECMAScript 5 中的 Object.keys() 方法。這個方法接收一個對象,返回一個包含可枚舉屬性的字串數組。
//屬性枚舉function Person(){}Person.prototype.name = "Nicholas";Person.prototype.age = 29;Person.prototype.job = "Software Engineer";Person.prototype.sayName = function(){ alert(this.name);};var keys = Object.keys(Person.prototype);alert(keys); //"name,age,job,sayName"var person1 = new Person();person1.name = ‘xxx‘;person1.age = 50;var person1keys = Object.keys(person1);alert(person1keys); //"xxx,50"
可以這樣擴充:
if(!Object.create){Object.create = function(o){function F(){}F.prototype = o;return new F();}}if(!Object.keys){Object.keys = function(o){var k = [], p;for(p in o){if(Object.prototype.hasOwnProperty.call(o,p)){k.push(p);}}return k;}}
更簡單的原型文法
function Person(){} Person.prototype = { name : "Nicholas", age : 29, job: "Software Engineer", sayName : function () { alert(this.name); }};var friend = new Person();alert(friend instanceof Object); //truealert(friend instanceof Person); //truealert(friend.constructor == Person); //falsealert(friend.constructor == Object); //true
原型的動態性
由於在原型中尋找值的過程是一次搜尋,因此對原型對象所做的任何改變都能夠立即從執行個體上反映出來,即時是先建立執行個體後改變原型。
//原型的動態性function Person(){} Person.prototype = { constructor: Person, name : "Nicholas", age : 29, job : "Software Engineer", sayName : function () { alert(this.name); }};var friend = new Person();Person.prototype.sayHi = function(){ alert("hi");};friend.sayHi(); //"hi"
如果重寫整個原型對象,會切斷執行個體中的指標( 調用建構函式會為執行個體添加一個指向最初原型的指標[[prototype]] )與最初原型之間的聯絡。
//重寫原型function Person(){}var friend = new Person(); Person.prototype = { constructor: Person, name : "Nicholas", age : 29, job : "Software Engineer", sayName : function () { alert(this.name); }};friend.sayName(); //error
原生對象的原型
原型模式的重要性不僅體現在建立自訂類型上,就是所有原生的參考型別,也都是採用原型模式建立的。所有原生參考型別(Object、Array、String...)都是在其建構函式的原型上定義了方法。
//原生對象的原型alert(typeof Array.prototype.sort); //"function"alert(typeof String.prototype.substring); //"function"String.prototype.startsWith = function (text) { return this.indexOf(text) == 0;};var msg = "Hello world!";alert(msg.startsWith("Hello")); //true
原型模式的問題
原型模式省略了為建構函式傳遞初始化參數這一環節,會造成所有執行個體在預設情況下都取得相同的屬性值。原型中所有的屬性是被很多執行個體共用的,執行個體一般都有屬於自己的屬性。
//原型問題function Person(){}Person.prototype = { constructor: Person, name : "Nicholas", age : 29, job : "Software Engineer", friends : ["Shelby", "Court"], sayName : function () { alert(this.name); }};var person1 = new Person();var person2 = new Person();person1.friends.push("Van");alert(person1.friends); //"Shelby,Court,Van"alert(person2.friends); //"Shelby,Court,Van"alert(person1.friends === person2.friends); //true
4. 組合使用建構函式模式和原型模式
建立自訂類型的最常見方式,就是組合使用建構函式模式和原型模式。建構函式用於定義執行個體屬性,原型模式用於定義方法和共用屬性。 這樣的組合,每個執行個體都有自己的一份執行個體屬性,又共用對方法的引用,最大限度的節省了記憶體。
//組合建構函式模式和原型模式function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.friends = ["Shelby", "Court"];}Person.prototype = { constructor: Person, sayName : function () { alert(this.name); }};var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");person1.friends.push("Van");alert(person1.friends); //"Shelby,Court,Van"alert(person2.friends); //"Shelby,Court"alert(person1.friends === person2.friends); //falsealert(person1.sayName === person2.sayName); //true
這種建構函式與原型混合的模式,是目前是用最廣泛、認同度最高的一種建立自訂類型的方法。這是用來自訂類型的一種預設模式。
5. 動態原型模式
動態原型模式把所有資訊都封裝在建構函式中,而通過在建構函式中初始化原型,又保持同時使用建構函式和原型的優點。
//動態原型模式function Person(name, age, job){//屬性this.name = name;this.age = age;this.job = job;//方法if (typeof this.sayName != "function"){ Person.prototype.sayName = function(){ alert(this.name); };}}var friend = new Person("Nicholas", 29, "Software Engineer");friend.sayName();
使用動態原型模式,不能使用對象字面量重寫原型。
6. 寄生建構函式模式
7. 穩妥建構函式模式
繼承
許多OO語言支援兩種繼承:介面繼承、實現繼承。介面繼承只繼承方法簽名,實現繼承則繼承實際的方法。在ECMAScript中無法實現介面繼承,因為函數沒有簽名。所以ECMAScript只支援實現繼承,實現繼承主要是依靠原型鏈來實現的。
1. 原型鏈
原型鏈的基本思想是利用原型讓一個參考型別繼承另一個參考型別的屬性和方法。
建構函式、原型、執行個體的關係:每個建構函式都有一個原型對象,原型對象都包含一個指向建構函式的指標( constructor ),執行個體都包一個指向原型對象的內部指標( [[prototype]] __proto__ )。
如果讓原型對象等於另一個類型的執行個體,此時的原型對象將包含一個指向另一個原型的指標,相應的,另一個原型中也包含著一個指向另一個建構函式的指標。假如另一個原型又是另一個類型的執行個體,這種關係依然成立,如此層層遞進,就構成了執行個體與原型的鏈條。這就是所謂原型鏈的基本概念。
//原型鏈//SuperTypefunction SuperType(){ this.property = true;}SuperType.prototype.getSuperValue = function(){ return this.property;};//SubTypefunction SubType(){ this.subproperty = false;}//繼承了SuperTypeSubType.prototype = new SuperType();SubType.prototype.getSubValue = function (){ return this.subproperty;};//instancevar instance = new SubType();alert(instance.getSuperValue()); //true//原型和執行個體的關係 1alert(instance instanceof Object); //truealert(instance instanceof SuperType); //truealert(instance instanceof SubType); //true//原型和執行個體的關係 2alert(Object.prototype.isPrototypeOf(instance)); //truealert(SuperType.prototype.isPrototypeOf(instance)); //truealert(SubType.prototype.isPrototypeOf(instance)); //true
//原型鏈關係圖
所有的參考型別都繼承了 Object,這個繼承也是通過原型鏈實現的。
SubType繼承了SuperType, SuperType繼承了Object. 當調用instance.toString()時,實際上調用的是儲存在Object.prototype中的那個toString()方法.
//謹慎的定義方法
子類型有時候需要重寫超類型中的某個方法,或者添加超類型中不存在的方法,給原型鏈加方法的代碼一定要放在替換原型的語句之後。
//原型鏈的問題
//原型鏈的問題function SuperType(){ this.colors = ["red", "blue", "green"];}function SubType(){}SubType.prototype = new SuperType();var instance1 = new SubType();instance1.colors.push("black");alert(instance1.colors); //"red,blue,green,black"var instance2 = new SubType();alert(instance2.colors); //"red,blue,green,black"
SuberType建構函式定義了一個colors屬性,SubType通過原型鏈繼承SuperType的一個執行個體,因此SubType.prototype變成了SuperType的一個執行個體,也擁有一個自己的colors屬性, 所有的SubType執行個體都共用這個屬性。對instance1.colors的修改也會通過instance2.colors反映出來。
建立子類型的執行個體時,不能向超類型的建構函式傳遞參數。實際上是沒有辦法在不影響所有對象執行個體的情況下,給超類的建構函式傳遞參數。
2. 借用建構函式
3. 組合繼承
4. 原型式繼承 - ‘現代’無類繼承模式
function object(o){function F(){}F.prototype = o;return new F();}if(!Object.create){Object.create = function(o){function F(){}F.prototype = o;return new F();}}
ECMAScript新增了 Object.create() 方法正常化了原型式繼承。這方法介紹兩個參數:一個用作新對象原型的對象、一個為新對象定義額外屬性的對象。在傳入一個參數的情況下,Object.create() 和 object()方法類似。
5. 寄生式繼承
6. 寄生組合式繼承
function object(o){ function F(){} F.prototype = o; return new F();}function inheritPrototype(subType, superType){ var prototype = object(superType.prototype); //create object prototype.constructor = subType; //augment object subType.prototype = prototype; //assign object}function SuperType(name){ this.name = name; this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function(){ alert(this.name);};function SubType(name, age){ SuperType.call(this, name); this.age = age;}inheritPrototype(SubType, SuperType);SubType.prototype.sayAge = function(){ alert(this.age);};var instance1 = new SubType("Nicholas", 29);instance1.colors.push("black");alert(instance1.colors); //"red,blue,green,black"instance1.sayName(); //"Nicholas";instance1.sayAge(); //29var instance2 = new SubType("Greg", 27);alert(instance2.colors); //"red,blue,green"instance2.sayName(); //"Greg";instance2.sayAge(); //27
在這個例子中,它只調用了一次 SuperType 建構函式,避免了在 SubType.prototype 上建立不必要的屬性。原型鏈也保持不變,還能正常使用 instanceof 和 isPrototypeOf()。普遍認為寄生組合式繼承是參考型別最理想的繼承方式。
第6章主要介紹了物件導向相關知識。建立對象:原廠模式、建構函式模式、原型模式、組合使用建構函式模式和原型模式... 實現繼承:原型式、寄生式、寄生組合式... 這一章需要深刻理解,是JS能否走得更遠的重要基礎。
讀書時間《JavaScript進階程式設計》二:物件導向