prototype.js参考

JavaScript类扩展

prototype.js 类库实现强大功能的一种途径是扩展已有的JavaScript 类。

Object的扩展

MethodKindArgumentsDescription
extend(destination, source) static destination: any object, source: any object提供一种通过拷贝所有源以象属性和函数到目标函数实现继承的方法
inspect(targetObj)statictargetObj: any object返回可读性好关于目标对象的文字描述,如果对象实例没有定义一个inspect函数,默认返回toString函数的值。

对Number的扩展

Method Kind ArgumentsDescription
toColorPart() instance (none)返回数字的十六进制表示形式。在把一个RGB数字转换成HTML表现形式时很有用。
succ()instance(none) 返回下一个数字,这个方法可用于迭代调用场景中。
times(iterator)instanceiterator: a function object conforming to Function(index)Calls the iterator function repeatedly passing the current index in the index argument. 反复调用iterator函数并传递当前index到iterator的index参数。

下面的例子用提示框显示0-9。


Function扩展

MethodKindArgumentsDescription
bind(object) instance object: the object that owns the method返回function的实例,这个实例和源function的结构一样,但是它已被绑定给了参数中提供的object,就是说,function中的this指针指向参数object。
bindAsEventListener(object)instanceobject: the object that owns the method用法和上面的bind一样,区别在于用来绑定事件。

让我们看看如何运用这些扩展。


Test?

对String的扩展

MethodKindArgumentsDescription
stripTags()instance(none)返回一个把所有的HTML或XML标记都移除的字符串。
stripScripts() instance (none)返回一个把所有的script都移除的字符串。
escapeHTML()instance(none)返回一个把所有的HTML标记合适的转义掉的字符串。
unescapeHTML()instance(none)escapeHTML()的反转。
extractScripts()instance(none)返回一个包含在string中找到的所有<script>的数组。
evalScripts()instance(none)执行在string中找到的所有<script>。
toQueryParams()instance(none)把querystring分割才一个用parameter name做index的联合Array,更像一个hash。
parseQuery()instance(none)和toQueryParams()一样.
toArray()instance(none)把字符串转换成字符数组.
camelize()instance(none)转换一个以连字符连接的字符串成一个骆驼法样式的字符串。比如,这个函数在写代码时,把它做为一个样式工具使用是很有用的。

对  Array的扩展

因为array扩展于enumerable,所以所有enumberable对象的函数,array都是可以使用的,除此之外,下面的这些也是已经实现了的。

MethodKindArgumentsDescription
clear() instance (none)清空。
compact()instance(none)返回一个不包括源array中null或undefined元素的array,此方法不改变源array。
first()instance(none)返回array的第一个对象。
flatten()instance(none)通过递归组合array每个元素的子元素(如果该元素也是array)来返回一个“扁平的”一维的array。
indexOf(value)instancevalue: what you are looking for.返回给出数字位置(从0算起)的元素,如果在该位置没有找到对象,返回-1。
inspect()instance(none)重载inspect(),返回更好格式的反映Array每个元素的字符描述。
last()instance(none)返回最后一个元素。
reverse([applyToSelf])instanceapplyToSelf: indicates if the array itself should also be reversed. 反转Array中元素的顺序,如果没有给出参数,或参数为true,则源Array中元素的顺序也反转,否则源Array保持不变。
shift()instance(none)返回Array的第一个元素并从Array中移除它,Array的Length-1。
without(value1 [, value2 [, .. valueN]])instancevalue1 ... valueN: values to be excluded if present in the array. 返回一个把参数列表中包含的元素从源Array中排除的Array。

document DOM扩展

MethodKindArgumentsDescription
getElementsByClassName(className [, parentElement]) instance className: name of a CSS class associated with the elements, parentElement: object or id of the element that contains the elements being retrieved.返回所有CSS className属性等于className参数的元素,如果没有给出parentElement,那么将搜索document body。(此处使用document.body我觉得不如使用document,因为有时有的页面没有body) 

Event扩展

PropertyTypeDescription
KEY_BACKSPACE Number Number8: Constant. Code for the Backspace key.
KEY_TABNumber9: Constant. Code for the Tab key.
KEY_RETURNNumber13: Constant. Code for the Return key.
KEY_ESCNumber27: Constant. Code for the Esc key.
KEY_LEFTNumber37: Constant. Code for the Left arrow key.
KEY_UPNumber38: Constant. Code for the Up arrow key.
KEY_RIGHTNumber39: Constant. Code for the Right arrow key.
KEY_DOWNNumber40: Constant. Code for the Down arrow key.
KEY_DELETENumber46: Constant. Code for the Delete key.
observers:ArrayList of cached observers. Part of the internal implementation details of the object.

MethodKindArgumentsDescription
element(event)staticevent: an Event object返回事件源对象。
isLeftClick(event)staticevent: an Event object如果点击了鼠标左键,返回true.
pointerX(event)staticevent: an Event object返回鼠标的X座标。
pointerY(event)staticevent: an Event object返回鼠标的Y座标。
stop(event)staticevent: an Event object使用此函数来中断事件的默认行为并阻止传递(冒泡)。
findElement(event, tagName)staticevent: an Event object, tagName: name of the desired tag.从事件源对象开始向上搜索DOM树,直到找到第一个符合tagName的元素
observe(element, name, observer, useCapture)staticelement: object or id, name: event name (like 'click', 'load', etc), observer: function to handle the event, useCapture: if true, handles the event in the capture phase and if false in the bubbling phase.为对象的某个事件增加一个处理函数。
stopObserving(element, name, observer, useCapture)staticelement: object or id, name: event name (like 'click'), observer: function that is handling the event, useCapture: if true handles the event in the capture phase and if false in the bubbling phase.和上面的函数相反。
_observeAndCache(element, name, observer, useCapture)static 私有函数,别管它。
unloadCache() static (none)私有函数,别管它。从内存中清除所有的observers缓存。

下面代码演示如何给window添加一个load事件处理函数。

 
   

在prototype.js中定义新的对象和类

另一个这个程序包帮助你的地方就是提供许多既支持面向对象设计理念又有共通功能的许多对象。

The PeriodicalExecuter object

这个对象提供一定间隔时间上重复调用一个方法的逻辑。

MethodKindArgumentsDescription
[ctor](callback, interval) constructor callback: a parameterless function, interval: number of seconds创建这个对象的实例将会重复调用给定的方法。

PropertyTypeDescription
callback Function() 被调用的方法,该方法不能传入参数。
frequencyNumber以秒为单位的间隔。
currentlyExecutingBoolean表示这个方法是否正在执行。

The Prototype object

Prototype 没有太重要的作用,只是声明了该程序包的版本 。

PropertyTypeDescription
VersionString版本。
emptyFunction Function() 空函数。
KFunction(obj)一个仅仅回传参数的函数。
ScriptFragmentString识别script的正则式。

The Enumerable object

Enumberable对象能够已更优雅的方式实现对列表样式的结构进行枚举。

很多其它的对象通过扩展自Enumberable对象来得到这些有用的接口。

MethodKindArgumentsDescription
each(iterator) instance iterator: a function object conforming to Function(value, index)把每个element做为第一个参数,element的index作为第一个参数调用iterator函数。
all([iterator])instanceiterator: a function object conforming to Function(value, index)这个函数会用给出的iterator测试整个集合,如果集合中任一元素在iterator函数测试中返回false或null,那么这个函数返回false,否则返回true。如果没有给出iterator,那么就会测试所有的元素是不是不等于false和null。你可以简单的把它看成是“检测每个元素都为非空非负”。
any(iterator)instanceiterator: a function object conforming to Function(value, index), optional.这个函数会用给出的iterator测试整个集合,如果集合中任一元素在iterator函数测试中返回true,那么这个函数返回true,否则返回false。如果没有给出iterator,那么就会测试所有的元素是不是有一个不等于false和null。你可以简单的把它看成是“检测元素中是不是有非空非负的”。
collect(iterator)instanceiterator: a function object conforming to Function(value, index) 调用iterator函数根据集合中每个元素返回一个结果,然后按照原来集合中的顺序,返回一个Array。
detect(iterator)instanceiterator: a function object conforming to Function(value, index)集合中每个元素调用一次Iterator,返回第一个使Iterator返回True的元素,如果最终都没有为true的调用,那么返回null。
entries()instance(none)等于toArray().
find(iterator)instanceiterator: a function object conforming to Function(value, index)等于 detect().
findAll(iterator)instanceiterator: a function object conforming to Function(value, index)集合中每个元素调用Iterator,返回一个由所有调用Iterator返回结果等于true的元素组成的数组。和reject()相反。
grep(pattern [, iterator])instancepattern: a RegExp object used to match the elements, iterator: a function object conforming to Function(value, index) 用pattern参数正则表达式测试集合中的每个元素,返回一个包含所有匹配正则式的元素的Array,如果给出了Iterator,那个每个结果还要经过一下Iterator处理。
include(obj)instanceobj: any object 判断集合中包不包含指定对象。
inject(initialValue, iterator)instanceinitialValue: any object to be used as the initial value, iterator: a function object conforming to Function(accumulator, value, index) 用Iterator联接所有集合中的元素。Iterator在被调用时把上一次迭代的结果做为第一个参数传给accumulator。第一次迭代时,accurmelator等于initialValue,最后返回accumulator的值。
invoke(methodName [, arg1 [, arg2 [...]]])instancemethodName: name of the method that will be called in each element, arg1..argN: arguments that will be passed in the method invocation.集合中的每个元素调用指定的函数(查看源代码可以发现指定函数被调用时,this指针被传成当前元素),并传入给出的参数,返回调用结果组成的Array。
map(iterator)instanceiterator: a function object conforming to Function(value, index)同collect().
max([iterator])instanceiterator: a function object conforming to Function(value, index)返回集合中元素的最大值,或调用Iterator后返回值的最大值(如果给出了Iterator的话)。
member(obj)instanceobj: any objectinclude().
min([iterator])instanceiterator: a function object conforming to Function(value, index)返回最小值,参见max()。
partition([iterator])instanceiterator: a function object conforming to Function(value, index)返回一个包含两个Array的Array,第一个Array包含所有调用Iterator返回True的元素,第二个Array包含剩下的元素。如果Iterator没有给出,那么就根据元素本身判断。
pluck(propertyName)instancepropertyName name of the property that will be read from each element. This can also contain the index of the element返回每个元素的指定属性名的属性的值组成的Array。
reject(iterator)instanceiterator: a function object conforming to Function(value, index)和  findAll()相反(返回所有等于false的元素).
select(iterator)instanceiterator: a function object conforming to Function(value, index)findAll().
sortBy(iterator)instanceiterator: a function object conforming to Function(value, index)根据每个元素调用Iterator返回的值进行排序返回一个Array。
toArray()instance(none)返回由集合所有元素组成的一个Array。
zip(collection1[, collection2 [, ... collectionN [,transform]]])instancecollection1 .. collectionN: enumerations that will be merged, transform: a function object conforming to Function(value, index)合并每个给出的集合到当前集合。合并操作返回一个新的array,这个array的元素个数和原集合的元素个数一样,这个array的每个元素又是一个子array,它合并了所有集合中相同index的元素。如果transform函数被指定,那么array的每个元素还会调用transform函数先做处理。举个例子: [1,2,3].zip([4,5,6], [7,8,9]).inspect() 返回 "[ [1,4,7],[2,5,8],[3,6,9] ]"

The Hash object

 Hash对象实现一种Hash结构,也就是一个Key:Value对的集合。

Hash中的每个Item是一个有两个元素的array,前一个是Key,后一个是Value,每个Item也有两个不需加以说明的属性,key和value。

MethodKindArgumentsDescription
keys()instance(none)返回所有Item的key的集合的一个array。
values() instance (none)返回所有Item的value的集合的一个array。
merge(otherHash)instanceotherHash: Hash object合并给出的Hash,返回一个新Hash。
toQueryString()instance(none)以QueryString那样的样式返回hash中所有的item,例如: 'key1=value1&key2=value2&key3=value3'
inspect()instance(none)用一种合适的方法显示hash中的key:value对。

The ObjectRange class

继承自  Enumerable

用上、下边界描述一个对象区域。

PropertyTypeKindDescription
start(any) instance

range的下边界

end(any)instancerange的上边界
exclusiveBooleaninstance决定边界自身是不是range的一部分。

MethodKindArgumentsDescription
[ctor](start, end, exclusive)constructorstart: the lower bound, end: the upper bound, exclusive: include the bounds in the range?创建一个range对象,从start生成到end,这里要注意的是,start和end必段类型一致,而且该类型要有succ()方法。
include(searchedValue) instance searchedValue: value that we are looking for检查一个value是不是在range中。

The Class object

在这个程序包中 Class 对象在声明其他的类时候被用到 。用这个对象声明类使得新类支持 initialize() 方法,他起构造方法的作用。

看下面的例子

//declaring the class
var MySampleClass = Class.create();

//defining the rest of the class implmentation
MySampleClass.prototype = {

   initialize: function(message) {
this.message = message;
   },

   showMessage: function(ajaxResponse) {
      alert(this.message);
   }
};

//now, let's instantiate and use one object
var myTalker = new MySampleClass('hi there.');
myTalker.showMessage(); //displays alert

MethodKindArgumentsDescription
create(*) instance (any)定义新类的构造方法。

The Ajax object

这个对象被用作其他提供AJAX功能的类的根对象。 

PropertyTypeKindDescription
activeRequestCountNumberinstance正在处理中的Ajax请求的个数。

MethodKindArgumentsDescription
getTransport() instance (none)返回新的XMLHttpRequest 对象。

The Ajax.Responders object

继承自 Enumerable

这个对象维持一个在Ajax相关事件发生时将被调用的对象的列表。比如,你要设置一个全局钩子来处理Ajax操作异常,那么你就可以使用这个对象。

PropertyTypeKindDescription
respondersArray instance 被注册到Ajax事件通知的对象列表。

MethodKindArgumentsDescription
register(responderToAdd)instanceresponderToAdd: object with methods that will be called.被传入参数的对象应包含名如Ajax事件的系列方法(如onCreate,onComplete,onException)。通讯事件引发所有被注册的对象的合适名称的函数被调用。
unregister(responderToRemove)instanceresponderToRemove: object to be removed from the list. 从列表中移除。
dispatch(callback, request, transport, json)instancecallback: name of the AJAX event being reported, request: the Ajax.Request object responsible for the event, transport: the XMLHttpRequest object that carried (or is carrying) the AJAX call, json: the X-JSON header of the response (if present) 遍历被注册的对象列表,找出有由callback参数决定的那个函数的对象。然后向这些函数传递其它的三个参数,如果Ajax响应中包含一个含有JSON内容的X-JSON HTTP头,那么它会被热行并传入json参数。如果事件是onException,那么transport参数会被异常代替,json不会传递。

The Ajax.Base class

这个类是其他在Ajax对象中定义的类的基类。

MethodKindArgumentsDescription
setOptions(options) instance options: AJAX options设定AJAX操作想要的选项。
responseIsSuccess()instance(none)返回 true 如果AJAX操作成功,否则为 false
responseIsFailure()instance(none)responseIsSuccess() 相反。

The Ajax.Request class

继承自 Ajax.Base

封装 AJAX 操作

PropertyTypeKindDescription
EventsArraystatic在AJAX操作中所有可能报告的事件/状态的列表。这个列表包括: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'
transportXMLHttpRequestinstance承载AJAX操作的 XMLHttpRequest 对象。
url string instance 请求的URL。

MethodKindArgumentsDescription
[ctor](url, options)constructorurl: the url to be fetched, options: AJAX options创建这个对象的一个实例,它将在给定的选项下请求url。onCreate事件在调用constructor事被激发。 重要: 如果选择的url受到浏览器的安全设置,他会一点作用也不起。 很多情况下,浏览器不会请求与当前页面不同主机(域名)的url。 你最好只使用本地url来避免限制用户配置他们的浏览器(谢谢Clay)
evalJSON() instance (none)这个方法显然不会被外部调用。它在Ajax响应中含有X-JSON HTTP头时用于内部调用执行这些内容。
evalReponse()instance(none)这也方法显然不会被外部调用,如果Ajax响应含有一个值为text/javascript的Cotent-Type头,那么这个方法就用被调用执行响应体。
header(name)instancename: HTTP header name引用Ajax响应的头的内容,在Ajax访问结束后再调用这个方法。
onStateChange()instance(none)这个方法通常不会被外部调用。 当AJAX请求状态改变的时候被这个对象自己调用。
request(url) instance url: url for the AJAX call这个方法通常不会被外部调用。已经在构造方法中调用了。
respondToReadyState(readyState)instancereadyState: state number (1 to 4)这个方法通常不会被外部调用。 当AJAX请求状态改变的时候被这个对象自己调用。
setRequestHeaders()instance(none)这个方法通常不会被外部调用。 被这个对象自己调用来配置在HTTP请求要发送的HTTP报头。

The options argument object

An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.

PropertyTypeDefaultDescription
methodString'post'HTTP 请求方式。
parameters String ''在HTTP请求中传入的url格式的值列表。
asynchronousBooleantrue指定是否做异步 AJAX 请求。
postBodyStringundefined在HTTP POST的情况下,传入请求体中的内容。
requestHeadersArrayundefined和请求一起被传入的HTTP头部列表, 这个列表必须含有偶数个项目, 任何奇数项目是自定义的头部的名称, 接下来的偶数项目使这个头部项目的字符串值。 例子:['my-header1', 'this is the value', 'my-other-header', 'another value']
onXXXXXXXXFunction(XMLHttpRequest, Object)undefined在AJAX请求中,当相应的事件/状态形成的时候调用的自定义方法。 例如 var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. 这个方法将被传入一个参数, 这个参数是承载AJAX操作的 XMLHttpRequest 对象,另一个是包含被执行X-JSON响应HTTP头。
onSuccessFunction(XMLHttpRequest, Object)undefined当AJAX请求成功完成的时候调用的自定义方法。 这个方法将被传入一个参数, 这个参数是承载AJAX操作的 XMLHttpRequest 对象,另一个是包含被执行X-JSON响应HTTP头。
onFailureFunction(XMLHttpRequest, Object)undefined当AJAX请求完成但出现错误的时候调用的自定义方法。这个方法将被传入一个参数, 这个参数是承载AJAX操作的 XMLHttpRequest 对象,另一个是包含被执行X-JSON响应HTTP头。
onExceptionFunction(Ajax.Request, exception) undefined 当一个在客户端执行的Ajax发生像无效响应或无效参数这样的异常情况时被调用的自定义函数。它收到两个参数,包含异常Ajax操作的Ajax.Request对象和异常对象。
insertionan Insertion classundefined一个能决定怎么样插入新内容的类,能 Insertion.Before, Insertion.Top, Insertion.Bottom, 或 Insertion.After. 只能应用于Ajax.Updater 对象.
evalScriptsBooleanundefined, false决定当响应到达的时候是否执行其中的脚本块,只在 Ajax.Updater 对象中应用。
decayNumberundefined, 1决定当最后一次响应和前一次响应相同时在 Ajax.PeriodicalUpdater 对象中的减漫访问的次数, 例如,如果设为2,后来的刷新和之前的结果一样, 这个对象将等待2个设定的时间间隔进行下一次刷新, 如果又一次一样, 那么将等待4次,等等。 不设定这个只,或者设置为1,将避免访问频率变慢。
frequencyNumberundefined, 2用秒表示的刷新间的间隔,只能应用于 Ajax.PeriodicalUpdater  对象。