prototype.js 参考(三)

xiaoxiao2026-09-21  4

JavaScript类扩展 prototype.js 类库实现强大功能的一种途径是扩展已有的JavaScript 类。 对 Object的扩展 Method Kind Arguments Description extend(destination, source) static destination: any object, source: any object 提供一种通过拷贝所有源以象属性和函数到目标函数实现继承的方法 inspect(targetObj) static targetObj: any object 返回可读性好关于目标对象的文字描述,如果对象实例没有定义一个inspect函数,默认返回toString函数的值。 对Number的扩展 Method Kind Arguments Description toColorPart() instance (none) 返回数字的十六进制表示形式。在把一个RGB数字转换成HTML表现形式时很有用。 succ() instance (none) 返回下一个数字,这个方法可用于迭代调用场景中。 times(iterator) instance iterator: 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()" οnclick="demoTimes()"> 对 Function扩展 Method Kind Arguments Description bind(object) instance object: the object that owns the method 返回function的实例,这个实例和源function的结构一样,但是它已被绑定给了参数中提供的object,就是说,function中的this指针指向参数object。 bindAsEventListener(object) instance object: 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的扩展 Method Kind Arguments Description 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) 转换一个以连字符连接的字符串成一个骆驼法样式的字符串。比如,这个函数在写代码时,把它做为一个样式工具使用是很有用的。
转载请注明原文地址: https://www.6miu.com/read-5052875.html

最新回复(0)