發表文章

目前顯示的是 2月, 2016的文章

JavaScript Object Oriented Programming

圖片
JavaScript Object Oriented Programming 關於JavaScript Object Oriented Programming,會寫這一系列的文章是因為希望自己的JavaScript程式碼能更物件導向、更模組化。這一系列的文章有以下的內容...

JavaScript Object Oriented Programming - Early and Late Binding

圖片
JavaScript Object Oriented Programming - Early and Late Binding JavaScript在呼叫的時候設定this的值,而這個this的值有可能不是我們預期的結果。下面有幾個範例。 this的值並非預期的狀況 以下都會由Menu這個建構子作為範例。 function Menu(elem){ //... }; var menu = new Menu(document.createElement('div'));

JavaScript Object Oriented Programming - Exceptions

圖片
JavaScript Object Oriented Programming - Exceptions 「例外(Exceptions)」是一個特別且重要的處理錯誤的方法。

JavaScript Object Oriented Programming - Factory Constructor Pattern

圖片
JavaScript Object Oriented Programming - Factory Constructor Pattern 「Factory Constructor Pattern」不使用new來宣告新物件,新物件用function call來建立,如下: var animal = Animal('fox'); var rabbit = Rabbit('rab');

JavaScript Object Oriented Programming - All-in-one Constructor Pattern

圖片
JavaScript Object Oriented Programming - All-in-one Constructor Pattern 所有的method和property都放在consctructor中,而不使用prototype。 Declaration function Animal(name){ this.name = name; this.run = function(){ console.log('running '+ this.name); } }; var animal = new Animal('Foxie'); animal.run();

JavaScript Object Oriented Programming - Pseudo-Classical Pattern

圖片
JavaScript Object Oriented Programming - Pseudo-Classical Pattern Pseudo-class declaration 在pseudo-classical pattern中,物件是由「建構子」(constructor)這個函式所建立,並把method放到建構子的prototype中。

JavaScript Object Oriented Programming - The "instanceof" operator

圖片
JavaScript Object Oriented Programming - The "instanceof" operator The instanceof operator instanceof 允許檢查物件是否為給定的constructor所產生的。 function Rabbit(){}; var rabbit = new Rabbit(); console.log(rabbit instanceof Rabbit); //ture rabbit的constructor的確是Rabbit。

JavaScript Object Oriented Programming - The "constructor" property

圖片
constructor 物件有內建的屬性「constructor」,意即「參考建立此物件的function」。 範例 我們來建立一個簡單的constructor,然後看看新的物件是否有正確的constructor的值。 function Rabbit(){}; var rabbit = new Rabbit(); console.log(rabbit.constructor == Rabbit); //true

JavaScript Object Oriented Programming - Extending Natives

圖片
Object Oriented Programming - Extending Natives Native JavaScript物件將method存在prototype中。例如:當一個新的物件被建立,內容為空,但為何可以使用toString這個method?(參考下面的程式碼) var obj = { }; console.log( obj.toString() ); 這是因為 var obj = {}; ( 即 var obj = new Object(); )。而Object是Native JavaScript的建構式,obj由Object所產生,因此 obj.__proto__ == Object.prototype; 。所以,所有在Object.prototype中的屬性,obj皆可使用(包含 Object.prototype.toString )。這就是為什麼obj可以使用 toString 這個method了。對於Array、Function和其他物件也是相同的道理,而它們的method即在Array.prototype、Function.prototype等。