首先,有个单例对象,它上面挂了很多静态工具方法。其中有一个是each,用来遍历数组或对象。
代码如下:
var nativeForEach = [].forEach
var nativeMap = [].map
var util = {
each: function (obj, iterator, context) {
if (obj == null) return
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context)
} else if ( obj.length === +obj.length ) {
for (var i = 0; i < obj.length; i++) {
if (iterator.call(obj[i] || context, obj[i], i, obj) === true) return
}
} else {
for (var k in obj) {
if (iterator.call(obj[k] || context, obj[k], k, obj) === true) return
}
}
},
map: function(obj, iterator, context) {
var results = []
if (obj == null) return results
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context)
this.each(obj, function(val, i, coll) {
results[i] = iterator.call(context, val, i, coll)
})
return results
}
}
还有诸如every、some等对集合(Array,Hash)操作的工具函数。使用时采用util.xx方式。
如果定义了一个集合类,这个类内部有集合数据。
代码如下:
function Collection(data) {
this.data = data || []
// some other property
// this.xxx = yyy
}
Collection.prototype = {
// some method
}
可以很方便的把util上的方法拷贝到集合类上,如
代码如下:
function copyMethod(clazz, obj) {
for (var method in obj) {
clazz.prototype[method] = function() {
var args = [].slice.call(arguments)
var target = this.data
新闻热点
疑难解答
图片精选