Prototype學習工具函數學習($方法)_prototype
來源:懂視網
責編:小采
時間:2020-11-27 20:43:28
Prototype學習工具函數學習($方法)_prototype
Prototype學習工具函數學習($方法)_prototype:$ $$ $A $F $H $R $w Try.these document.getElementsByClassName $方法——被成為瑞士軍刀(Swiss Army knife) If provided with a string, returns the element in the document with matching ID;
導讀Prototype學習工具函數學習($方法)_prototype:$ $$ $A $F $H $R $w Try.these document.getElementsByClassName $方法——被成為瑞士軍刀(Swiss Army knife) If provided with a string, returns the element in the document with matching ID;

$
$$
$A
$F
$H
$R
$w
Try.these
document.getElementsByClassName
$方法——被成為瑞士軍刀(Swiss Army knife)
If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element. Takes in an arbitrary number of arguments. All elements returned by the function are extended with Prototype DOM extensions.
代碼如下:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length;
i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
首先檢查傳進來的參數長度:
如果長度等于1,則判斷傳進來的參數是否為String,如果傳進來的是String,則調用getElementById方法取得相應的對象,最后讓返回的對象繼承Element的所有方法,這樣返回的對象將可以直接調用Element對象里面定義的各種方法。例如
代碼如下:
// Note quite OOP-like...
Element.hide('itemId');
// A cleaner feel, thanks to guaranted extension
$('itemId').hide();
如果長度大于1,則遞歸調用$方法(elements.push($(arguments[i]));)就是說傳進來的參數可以是多維數組:
$(['A','B',['C','D',['E','F']]]),當然了返回的也是對象數組了。
如果長度等于0,返回undefined,即直接調用alert($())
詳細看一下Object.isString方法:
代碼如下:
function isString(object) {
return getClass(object) === "String";
}
//=====> getClass()
function getClass(object) {
return Object.prototype.toString.call(object)
.match(/^\[object\s(.*)\]$/)[1];
}
主要是通過Object對象的內部方法getClass來確定返回的對象是什么類型,在getClass中調用了Object的toString方法,然后通過正則表達式取出表示具體對象的字符串
Object.prototype.toString.call("2222") 返回"[object String]" 取得"String"
Object.prototype.toString.call(2222) 返回"[object Number]" 取得"Number"
Object.prototype.toString.call(/^$/) 返回"[object RegExp]" 取得"RegExp"
這里為什么要用Object的toString方法呢,因為如果直接調用"2222".toString()將返回"2222",也就是說從Object繼承而來的對象,重寫了toStirng方法,所以這里要調用Object的toString才行。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
Prototype學習工具函數學習($方法)_prototype
Prototype學習工具函數學習($方法)_prototype:$ $$ $A $F $H $R $w Try.these document.getElementsByClassName $方法——被成為瑞士軍刀(Swiss Army knife) If provided with a string, returns the element in the document with matching ID;