一、函数作为参数传递
1、回调函数 ajax异步请求
// callback为待传入的回调函数
var getUserInfo = function(userId, callback) {
$.ajax("http://xxx.com/getUserInfo?" + userId, function(data) {
if (typeof callback === "function") {
callback(data);
}
});
}
getUserInfo(13157, function(data) {
alert (data.userName);
});
2、Array.prototype.sort
//从小到大排列
[1, 4, 3].sort(function(a, b) {
return a - b;
});
// 输出: [1, 3, 4]
//从大到小排列
[1, 4, 3].sort(function(a, b) {
return b - a;
});
// 输出: [4, 3, 1]
二、函数作为返回值输出
判断数据的类型
var Type = {};
for (var i = 0, type; type = ['String', 'Array', 'Number'][i++];) {
(function(type) {
Type['is' + type] = function(obj) {
return Object.prototype.toString.call(obj) === '[object '+ type +']';
}
})(type)
};
Type.isArray([]); // 输出:true
Type.isString("str"); // 输出:true
单例模式
var getSingle = function(fn) {
var ret;
return function() {
return ret || (ret = fn.apply(this, arguments));
};
};