要讀懂 Prototype 的 AJAX 用法,得先理解它怎麼處理物件導向。這一篇整理 Prototype 的基礎類別工具與字串擴充方法。
建立一個類別:
var myClass = Class.create();
把 source 的所有屬性複製到 destination 上,是 Prototype 實作繼承的核心。
var myClass = Class.create();
myClass.prototype = {
initialize: function() {},
f1: function() { alert("do f1()"); },
f2: function() { alert("do f2()"); },
toString: function() { return "myClass"; }
};
var mySubClass = Class.create();
Object.extend(mySubClass.prototype, myClass.prototype); // 子類繼承父類
回傳物件的文字說明,方便除錯。若物件沒定義 inspect,則回退到 toString()。
var obj = new myClass(); alert(Object.inspect(obj));
回傳一個新函式,結構與原函式相同,但 this 被固定在指定的物件上。這是處理回呼函式時最實用的一招。
var obj = new myClass(); // 有 f1,this.name = "myClass" var obj2 = new myClass2(); // 有 f2,this.name = "myClass2" obj2.f2 = obj.f1.bind(obj2); obj2.f2(); // 輸出 "myClass2 from f1"
功能與 bind 相同,專門用於綁定事件。
var Watcher = Class.create();
Watcher.prototype = {
initialize: function(buttonid, message) {
this.button = $(buttonid);
this.message = message;
// 把按鈕的 onclick 綁到 this.showMessage,並固定 this
this.button.onclick = this.showMessage.bindAsEventListener(this);
},
showMessage: function() {
alert(this.message);
}
};
var watcher = new Watcher('btn', 'clicked');
週期性呼叫某個方法,省去自己管理 setInterval。
function setTime() {
$('divTime').innerHTML = (new Date()).toLocaleString();
}
new PeriodicalExecuter(setTime, 1); // 第二個參數是間隔秒數
Prototype 對 String 做了大量擴充,很多都是日常會用到的。
gsub(pattern, replacement)——全文替換:
"this is a test test".gsub(/test/, "new"); // this is a new new
truncate(length, truncation)——截斷字串,預設長度 30、尾字 "...":
var str = "this is a test test"; str.truncate(10); // this is ... str.truncate(14); // this is a t... str.truncate(10, "***"); // this is***
strip()——移除前後空白:
var str = "this is a test test "; str.strip().length; // 19 str.length; // 22
stripTags()——移除所有 HTML/XML 標籤:
"<table><tr><td>stripTagsDemo</td></tr></table>".stripTags(); // stripTagsDemo
stripScripts()——移除 <script> 區塊:
"this is a test<script>alert('ok')</script>".stripScripts();
// this is a test
evalScripts()——執行字串中所有的 script:
"this is a test<script>alert('ok')</script>".evalScripts(); // 跳出 ok
escapeHtml() / unescapeHtml()——HTML 轉義與還原:
"<table>...".escapeHtml(); // 把 < > 等轉成實體 "<table>...".unescapeHtml(); // 反向操作
toQueryParams()——把查詢字串轉成物件:
var arr = "a=1&b=2&c=3".toQueryParams();
for (i in arr) { alert(arr[i]); } // 1, 2, 3
toArray()——拆成字元陣列:
"test".toArray().each(function(item){ alert(item); }); // t e s t
extractScripts()——抽出所有 script 內容,以陣列回傳:
var str = "a<script>alert('ok')</script>";
str.extractScripts().each(function(item){ alert(item); });
camelize()——連字號轉駝峰命名:
"this-is-a-test".camelize(); // thisIsATest
Prototype 的這套設計,本質是在 JavaScript 原生的物件模型上加一層糖衣,讓它看起來更像傳統的類別語言。今天 ES6 的 class 語法與 Object.assign() 已經把這些需求標準化了(Object.assign 幾乎就是 Object.extend),而字串方法也大多能在 Lodash 或原生 API 中找到對應。讀懂這一層演變,比記住某個方法的名字更有價值。