SoFunction
Updated on 2025-04-14

Prototype Learning Tool Function Learning ($Method)

$
$$
$A
$F
$H
$R
$w


$Method—becomed a 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.
Copy the codeThe code is as follows:

function $(element) {
if ( > 1) {
for (var i = 0, elements = [], length = ; i < length;
i++)
($(arguments[i]));
return elements;
}
if ((element))
element = (element);
return (element);
}

First check the length of the parameters passed in:

If the length is equal to 1, it is determined whether the passed parameter is String. If the passed in, call the getElementById method to obtain the corresponding object, and finally let the returned object inherit all the methods of Element. In this way, the returned object can directly call the various methods defined in the Element object. For example
Copy the codeThe code is as follows:

// Note quite OOP-like...
('itemId');
// A cleaner feel, thanks to guaranted extension
$('itemId').hide();

If the length is greater than 1, the $ method is called recursively (($(arguments[i]));) means that the passed parameters can be a multi-dimensional array:
$(['A','B',['C','D',['E','F']]]), of course, the returned object array is also an object array.
If the length is equal to 0, undefined is returned, that is, alert($()) is called directly
Take a look at the method in detail:
Copy the codeThe code is as follows:

function isString(object) {
return getClass(object) === "String";
}

//=====> getClass()

function getClass(object) {
return (object)
.match(/^\[object\s(.*)\]$/)[1];
}

It mainly determines what type of the returned object is through the internal method of the Object object. The toString method of the Object is called in getClass, and then the string representing the specific object is taken out through a regular expression.

("2222") Return "[object String]" Get "String"

(2222) Return "[object Number]" Get "Number"



(/^$/) Return "[object RegExp]" Get "RegExp"

Why do you need to use the toString method of Object? Because if you call "2222".toString() directly, it will return "2222", which means that the object inherited from the Object has been rewritten toString method, so you need to call the toString of Object here.