日期:2014-05-16  浏览次数:20439 次

JS代码阅读
//通过predicate函数判断过滤数组
function filterArray(/*array*/a, /*boolean function*/ predicate) {
	var results = [];
	var length = a.length;	// In case predicate changes the length!
	for(var i = 0; i < length; i++) {
		var element = a[i];
		if (predicate(element)) results.push(element);
	}
	return results;
}

//Retrun the array of values that reaults when each of the elements
//Of the array a are passed to the function f
//返回a数组的所有值经过f函数运算后的结果数组
function mapArray(/*array*/a, /*function*/ f) {
	var r = [];				// to hold the results
	var length = a.length;	// In case f changes the length!
	for(var i = 0; i < length; i++) r[i] = f(a[i]);
	return r;
}


//给o对象绑定函数,并调用
function bindMethod(/*object*/o ,/*function*/ f) {
	return function() { return f.apply(o, arguments) }
}

//返回一个函数调用函数f,带有指定参数和任何额外的参数传递给函数
function bindArguments(/*function*/f /*, initial arguments...*/) {
	var boundArgs = arguments;
	return function() {
		//Build up an array of arguments. It start with the previously
		//bound arguments and is extended with the arguments passed new
		var args = [];
		for(var i= 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
		for(var i= 0; i < arguments.length; i++) args.push(arguments[i]);
		
		//Now invoke the function with these arguments
		return f.apply(this,args)
	}
}



//return an array that holds the names of the enumerable property of obj
//返回一个数组保存姓名的枚举属性对象
function getPropertyNames(/*object*/obj) {
	var r = [];
	for(name in obj) r.push(name);
	return r;
}

//Copy the enumerable properties of the object from to the object to.
//if to in null, a new object is created. the function returns to or the
//newly created object.
//复制的可枚举属性的对象从对象。如果无效,一个新的对象被创建。该函数返回或者新创建的对象。
function copyProperties(/*object*/ from, /*optional object*/ to) {
	if(!to) to = {};
	for(p in from) to[p] = from[p];
	return to;
}

//Copy the enumerable properties of the object from to the object to,
//but only the ones that are not already defined by to.
//This is useful, for example, when from contains default values that
//we want to use if they are not already defined in to.
//复制的可枚举属性的对象从对象,但只有那些没有已定义的。这是有用的,例如,当从包含默认值我们要使用如果他们没有已定义在。
function copyUndefinedProperties(/*objecr*/ from, /*objecr*/ to) {
	 for(p in from) {
	 	if(!p in to) to[p] = from[p];
	 }
}