1.惰性载入函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 创建了各个浏览器下面可以访问的xhr对象
function createXHR(){
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
// handleErr(e);
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xhr =null;
}
}
}
return xhr;
}
console.log(e);
// function handleErr(err){
// var errXHR = err;
// }
// 惰性函数
// 第二次运行时加载
function createXHR(){
var xhr = null;
if(typeof XMLHttpRequest!='undefined'){
xhr = new XMLHttpRequest();
createXHR=function(){
return new XMLHttpRequest();
}
}else{
try{
xhr = new ActiveXObject('Msxml2.XMLHTTp');
createXHR = function(){
return new ActiveXObject('Msxml2.XMLHTTP');
}
}catch(e){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
createXHR = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
}
}catch(e){
createXHR = function(){
return null;
}
}
}
}
return xhr;
}
</script>
</body>
</html>
2.函数柯里化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 合并参数 第一个函数的参数合并成整体的 传递给统一的函数
function add(num1,num2){
return num1+num2;
}
function totalAdd(num3){
return 50+add(1,2)
}
alert(totalAdd(50));
</script>
<script>
function curry(fn){
var args = Array.prototype.slice.call(arguments,1);
console.log('args...',args);
return function(){
var innerArgs = Array.prototype.slice.call(arguments);
console.log('innerArgs',innerArgs);
var finalArgs = args.concat(innerArgs);
console.log('.finalArgs...',finalArgs);
return fn.apply(this,finalArgs);
}
}
function add(num1,num2,num3){
return num1+num2+num3;
}
var t = curry(add,50)(1,2);
alert(t);
</script>
</body>
</html>
3.级联函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function classA(){
this.lian = "";
this.zui = "";
this.tui = "";
}
// 原型链的constructor指定回来
classA.prototype = {
setLian:function(){
this.lian = "红彤彤";
return this;
},
setZui:function(){
this.zui = "大嘴";
return this;
},
setTui:function(){
this.tui = "长腿欧巴"
}
};
var person = new classA();
// person.setLian();
// person.setZui();
// person.setTui();
// 级联函数,把相关属性的东西全部串起来
person.setLian().setZui().setTui();
console.log(person);
// $('#btn').html().val().attr();
</script>
</body>
</html>
by上面的例子其实不够经典也不够高级
本文看自前端常用的库和实用技术之JavaScript高级函数