日期:2014-05-16 浏览次数:20435 次
Ext为javascript的一些对象进行了扩展,主要有String、Array和Function,以下只介绍Ext.js中提到的方法,其他的后续再介绍
?
Ext为String扩展了方法 format,该方法为String的静态方法(类方法),可以把字符串中特殊写法({0},{1})用指定的变量替换
?
//定义带标记的字符串,并用传入的字符替换标记。每个标记必须是唯一的,而且必须要像{0},{1}...{n}
//这样地自增长。
//var cls = 'my-class', text = 'Some text';
//var s = String.format('{0} ' '{1}', cls, text);
//s现在是字符串:s now contains the string: 'my-class' 'Some text'
format : function(format){
var args = Ext.toArray(arguments, 1);
return format.replace(/\{(\d+)\}/g, function(m, i){
return args[i];
});
}
?
?Ext为Array扩展了方法 indexOf 和remove,这两个方法分别实现了索引和根据子元素删除对应的该元素
Ext.applyIf(Array.prototype, {
/**
* Checks whether or not the specified object exists in the array.
* @param {Object} o The object to check for
* @param {Number} from (Optional) The index at which to begin the search
* @return {Number} The index of o in the array (or -1 if it is not found)
*/
indexOf : function(o, from){
var len = this.length;
from = from || 0;
from += (from < 0) ? len : 0;
for (; from < len; ++from){
if(this[from] === o){
return from;
}
}
return -1;
},
/**
* Removes the specified object from the array. If the object is not found nothing happens.
* @param {Object} o The object to remove
* @return {Array} this array
*/
remove : function(o){
var index = this.indexOf(o);
if(index != -1){
this.splice(index, 1);
}
return this;
}
});
?
编者在实际开发中经常会用到以下两个方法,也很实用
?
/**
* 数组插入元素
* @param {} index 插入位置
* @param {} o 插入元素
* @return {}
*/
insert : function (index,o){
if(index <= 0){
return this.unshift(o);//插入到首元素
}
if(index >= this.length){
return this.push(o);//插入到末元素
}
var sub = this.slice(index, this.length);
this.length = index;
this.push(o);
for(var i = 0; i < sub.length; i++){
this.push(sub[i]);
}
return this;
},
/**
* 删除数组中指定的元素
* @param {} index
* @return {}
*/
removeAt : function(index){
if(index != -1){
this.splice(index, 1);
}
return this;
}
?
以下扩展String方法也很有用
Ext.applyIf(String,{
/**
* 把驼峰格式的字符串转换为-格式
* alert(humpToConnector('aaaBbbCcc','-')); //return aaa-bbb-ccc
* @param {} str
* @param {} conj
* @return {}
*/
humpToConnector : function(str, conj){
//str = !str ? str : String(str);
var index = str.search(/[A-Z]/);
if (index >= 0) {
var c = str.charAt(index);
return String.humpToConnector(str.substring(0, index) + conj
+ c.toLowerCase() + str.substring(index + 1), conj);
} else {
return str;
}
}
});
?
Ext对Function的扩展
?
createInterceptor方法
createInterceptor : function(fcn, scope){
var method = this;
return !Ext.isFunction(fcn) ?
this :
function() {
var me = this,
args = arguments;
fcn.target = me;
fcn.method = method;
return (fcn.apply(scope || me || window, args) !== false) ?
method.apply(me || window, args) :
null;
};
},
?
该方法实现了类似拦截器的功能,传递的参数fcn在原函数之前调用。如果fcn的返回值为false,则原函数不会被调用。即函数fcn拦截时,如果fcn返回false,将被拦截,true则执行。以下说明方法中的部分语句。
?
var method = this,因为是给Function.prototype扩展,因此其prototype上挂的所有的函数,函数内的this都是Fu