js bind实现解析


bind到底是什么,有什么作用

1.改变函数内部的作用域

2.返回一个函数(柯里化)


bind用法

fun.bind(this,arg1,arg2,...)
bind()方法会创建一个新的函数,称为绑定函数,fun方法在this环境下调用
该方法可传入两个参数,第一个参数作为this,第二个及以后的参数则作为函数的参数调用

var test=function(){
    console.log(this.x);
}
var o={
    x:1
}
test();  //undefined
test.bind(o)(); //1

第一次调用this指向global,第二次test.bind(o)() 这个this指向o,通过观察可以知道test.bind(o)此时是一个函数,说明bind返回的是一个函数。

传参方式:

var test=function(a,b,c){
    console.log("a="+a,"b="+b,"c="+c);
}
var o={
    x:1
}
test.bind(o)(1,2,3) //a=1 b=2 c=3
test.bind(o,1)(2,3) //a=1 b=2 c=3
test.bind(o,1)(); //a=1 b=undefined c=undefined
test.bind(o,1,2)();//a=1 b=2 c=undefined
test.bind(o,1,2,3)(); //相当于调用test(1,2,3)   a=1 b=2 c=3


简单实现一个bind函数

一个最简单的bind,每个function都有bind索要应该是一个Function的原型方法

Function.prototype.bind = function (context) {
    let self = this; //此时this指向 test
    let arg = Array.prototype.slice.call(arguments, 1);//转换成数组
    return function () {
        return self.apply(context, arg);
    }
}

var test = function (a, b, c) {
    console.log("x=" + this.x, "a=" + a, "b=" + b, "c=" + c);
}
var o = {
    x: 1
}

test.bind(o)(); //x=1 a=undefined b=undefined c=undefined
test.bind(o, 1)(2); //x=1 a=1 b=undefined c=undefined 此时 不支持传参

实现柯里化

Function.prototype.bind = function (context) {
    let self = this; //此时this指向 test
    let arg = Array.prototype.slice.call(arguments, 1);// 去掉第一个,转换成数组
    return function () {
        let innerArg = Array.prototype.slice.call(arguments);// 此时arguments为传进来的参数,转换成数组
        let totalArg = arg.concat(innerArg); // 拼接bind进来的参数与bind之后调用的参数 作为test的参数
        return self.apply(context, totalArg);
    }
}


var test = function (a, b, c) {
    console.log("x=" + this.x, "a=" + a, "b=" + b, "c=" + c);
}
var o = {
    x: 1
}
test.bind(o, 1)(2,3);  //x=1 a=1 b=2 c=3

原型链

Function.prototype.bind = function (context) {
    let self = this; //此时this指向 test
    let arg = Array.prototype.slice.call(arguments, 1);
    let fNOP = function () {};
    let fbound = function () {
        let innerArg = Array.prototype.slice.call(arguments);// 此时arguments为传进来的参数,转换成数组
        let totalArg = arg.concat(innerArg); // 拼接bind进来的参数与bind之后调用的参数 作为test的参数
        return self.apply(context, totalArg);
    }
    fNOP.prototype = this.prototype;
    fbound.prototype = new fNOP();
    return fbound;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容