所谓高阶函数是指可一把函数作为参数,或者是可以将函数作为返回值的函数(我们见得闭包函数就是高阶函数)。
function foo(x){
return function(){
return x;
}
}
一般地,有以下两种情况 1、函数可以作为参数被传递 2、函数可以作为返回值输出
forEach:
// 对于古董浏览器,如IE6-IE8
if (typeof Array.prototype.forEach != "function") {
Array.prototype.forEach = function (fn, context) {
for (var k = 0, length = this.length; k < length; k++) {
if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) {
fn.call(context, this[k], k, this);
}
}
};
}
=============================================
map:
让IE6-IE8浏览器也支持map方法:
if (typeof Array.prototype.map != "function") {
Array.prototype.map = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
arr.push(fn.call(context, this[k], k, this));
}
}
return arr;
};
}
=================================================
filter:
if (typeof Array.prototype.filter != "function") {
Array.prototype.filter = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
fn.call(context, this[k], k, this) && arr.push(this[k]);
}
}
return arr;
};
}
==============================================
some:
IE6-IE8扩展如下:
if (typeof Array.prototype.some != "function") {
Array.prototype.some = function (fn, context) {
var passed = false;
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
if (passed === true) break;
passed = !!fn.call(context, this[k], k, this);
}
}
return passed;
};
}
=========================================
every:
E6-IE8扩展(与some相比就是true和false调换一下):
if (typeof Array.prototype.every != "function") {
Array.prototype.every = function (fn, context) {
var passed = true;
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
if (passed === false) break;
passed = !!fn.call(context, this[k], k, this);
}
}
return passed;
};
}
==========================================
indexOf:
if (typeof Array.prototype.indexOf != "function") {
Array.prototype.indexOf = function (searchElement, fromIndex) {
var index = -1;
fromIndex = fromIndex * 1 || 0;
for (var k = 0, length = this.length; k < length; k++) {
if (k >= fromIndex && this[k] === searchElement) {
index = k;
break;
}
}
return index;
};
}
偏函数用法是指创建一个调用另一个部分——参数或变量已经预置的的函数——的函数的用法。
普通方法:
var toString=object.prototype.toString;
var isString=function(obj){
return toString.call(obj)=='[object String]';
};
var isFunction=function(obj){
return toString.call(obj)=='[object Function]';
};
..........
偏函数方法:
var isType=function(type){
return function(obj){
return tostring.call(obj)=='[object ' + type+ ' ]';
}
}