Home > Web Front-end > JS Tutorial > body text

Prototype 学习 工具函数学习($方法)_prototype

WBOY
Release: 2016-05-16 18:50:07
Original
1026 people have browsed it

$
$$
$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 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才行。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!