js学习总结----柯里化函数

柯里化函数函数思想:一个JS预处理的思想->利用函数执行可以形成一个不销毁的私有作用域的原理,把需要预先处理的内容都存在这个不销毁的作用域中,并且返回一个小函数,以后我们执行的都是小函数,在小函数中把之前预先存储的值进行一系列的操作。

下面是模拟函数的bind方法的myBind,具体代码如下

Function.prototype.myBind = function myBind(context){
    //this->fn
    var _this = this;
    var outerArg = Array.prototype.slice.call(arguments,1);
    //兼容
    if("bind" in Function.prototype){
        return this.bind.apply(this,[context].concat(outerArg));
    }
    //不兼容
    return function(){
        var innerArg = Array.prototype.slice.call(arguments,0);
        innerArg.length===0?innerArg[innerArg.length] = window.event:null;//解决ie里面不传递e,是传递window.event
        var arg = outerArg.concat(innerArg);
        _this.apply(context,arg)

    }
}
//把传递进来的callback这个方法中的this预先处理为context(模拟函数的bind方法,兼容ie6-8)
function bind(callback,context){
    context = context || window;
    var outerArg = Array.prototype.slice.call(arguments,2);//存储的参数
    return function(){
        var innerArg = Array.prototype.slice.call(arguments,0);//存储的e
        callback.apply(context,outerArg.cancat(innerArg));
    }
}

var obj = {name:"zhangsan"};
function fn(num1,num2){
    console.log(this,num1,num2);
}

window.setTimeout(fn.myBind(obj,100,200),1000);//这里把fn里面的this变成了obj
原文地址:https://www.cnblogs.com/diasa-fly/p/7300626.html