prototype.js 类库实现强大功能的一种途径是扩展已有的JavaScript 类。
| Method | Kind | Arguments | Description |
|---|---|---|---|
| extend(destination, source) | destination: any object, source: any object | 提供一种通过拷贝所有源以象属性和函数到目标函数实现继承的方法 | |
| inspect(targetObj) | static | targetObj: any object | 返回可读性好关于目标对象的文字描述,如果对象实例没有定义一个inspect函数,默认返回toString函数的值。 |
| Method | Arguments | Description | |
|---|---|---|---|
| toColorPart() | (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()" onclick="demoTimes()">
| Method | Kind | Arguments | Description |
|---|---|---|---|
| bind(object) | 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>
请稍等,评论加载中...