มาดูโครงสร้างง่ายๆ ของการเขียนโปรแกรมเชิง prototype ก่อน
Module
1 2 3 4 5 6 7 8 9 10 11 12 | var Site = { footerStatus:"showed", showFooter = function() { // showFooter = function(var1,var2,...) $('#footer').show(); this. footerStatus = "show"; }, hideFooter = function(){ $('#footer').hide(); this. footerStatus = "hide"; } // you can use .toggle() as well. } |
ยังดีว่าผมยังเคยเขียนเชิง prototype กับ ActionScript มาก่อน ไม่งั้นคงจะแอบงงอยู่บ้าง สำหรับคนไม่คุ้น ดูกันจริงๆ มันก็ไม่ต่างจากการเขียนเชิง Object-oriented สมัยใหม่สักเท่าไหร่หรอก พอถูไถไปได้บ้าง ไม่ยากๆ
ในตัวอย่าง ก็แยกให้เป็น module ซะเลย เป็นการแบ่งหน้าที่ของ module อย่างชัดเจน จุดที่ผมลืมบ่อยๆ เห็นจะเป็น comma ที่เป็นตัวแบ่ง function ครับ ลืมตลอด =='
เวลาเรียกใช้งานก็ง่ายๆ
Class
อีกหนึ่งส่วนสำคัญของการเขียนโปรแกรมเลย :)
อย่าลืม include prototype.js มาก่อนนะ ไม่งั้นเรียก Class ไม่เจอ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var Animal = Class.create(); Animal.prototype = { initialize: function(){ this.alive = true; this.full = false; }, eat: function(food){ if(food == "sticky-rice"){ this.full = true; alert(this.full); return this.full; } return false; } } var myPet = new Animal(); myPet.eat("pizza"); myPet.eat("sticky-rice"); // alert "true" |
Extend
การต่อเติมก็สำคัญ :)
1 2 3 4 5 6 7 8 | Object.extend(Animal.prototype, { dieNow: function() { this.alive = false; alert(this.alive); } } ); myPet.dieNow(); // alert "false" |
addMethods
ก็ไว้เพิ่ม method(หรือใครจะเรียก function) ให้กับ Dom element ในหน้าเว็บ
1 2 3 4 5 6 7 8 9 10 | Element.addMethods({
say: function(element, word){
if(!word)
alert(element.innerHTML);
else
alert(word);
}
});
$('footer').say();
$('footer').say("hello");
|
argument ตัวแรก ถูกบังคับให้เป็น element ของ Dom ตัว parameter ที่เราส่งไปเลยเป็น argument ตัวที่สอง
เบาะๆ แค่นี้ก่อน ผมง่วง =='
ข้อมูลจาก video ของปี๊บโด้ด