friping 发表于 2013-2-7 20:51:18

prototype.js 参考(三)

JavaScript类扩展
prototype.js 类库实现强大功能的一种途径是扩展已有的JavaScript 类。
对 Object的扩展
MethodKindArgumentsDescription
extend(destination, source)staticdestination: any object, source: any object提供一种通过拷贝所有源以象属性和函数到目标函数实现继承的方法
inspect(targetObj)statictargetObj: any object返回可读性好关于目标对象的文字描述,如果对象实例没有定义一个inspect函数,默认返回toString函数的值。
对Number的扩展
MethodKindArgumentsDescription
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。
<script>

function demoTimes(){

var n = 10;

n.times(function(index){

alert(index);

});

/***************************

* you could have also used:

*         (10).times( .... );

***************************/

}

</script>

<input type=button value="Test Number.times()" >

对 Function扩展
MethodKindArgumentsDescription
bind(object)instanceobject: the object that owns the method返回function的实例,这个实例和源function的结构一样,但是它已被绑定给了参数中提供的object,就是说,function中的this指针指向参数object。
bindAsEventListener(object)instanceobject: the object that owns the method用法和上面的bind一样,区别在于用来绑定事件。
让我们看看如何运用这些扩展。
<input type=checkbox id=myChk value=1> Test?

<script>

//declaring the class

var CheckboxWatcher = Class.create();

//defining the rest of the class implementation

CheckboxWatcher.prototype = {

initialize: function(chkBox, message) {

this.chkBox = $(chkBox);

this.message = message;

//assigning our method to the event


this.chkBox.onclick =
this.showMessage.bindAsEventListener(this);

},
showMessage: function(evt) {
alert(this.message + ' (' + evt.type + ')');
}
};
var watcher = new CheckboxWatcher('myChk', 'Changed');
</script>
对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)转换一个以连字符连接的字符串成一个骆驼法样式的字符串。比如,这个函数在写代码时,把它做为一个样式工具使用是很有用的。
页: [1]
查看完整版本: prototype.js 参考(三)