手写bind
  X1N8l2v9m1kd 29天前 28 0

首先写一个bind的简单示例:

'use strict'
function fn() {
  console.log('this::', this)
  console.log('arguments::', arguments)
}
// fn() // 这里调用时this 在严格模式下是undefined,非严格模式下是Window
var fn1 = fn.bind('str', 1, 2, 3); // 这里把this改为了'str'
fn1(4, 5, 6);

fn1的调用结果如下:
image

根据以上示例总结几个bind的特征:
① 可以提前绑定this及参数
② 不会立刻调用,返回一个新函数
③ 新的函数调用时也可以传参

1. 初步雏形( 最后有完整代码 )
    Function.prototype.mybind = function (asThis) {
        console.log('mybind.....')
    }
    function fn() {

    }
    fn.mybind();
2.提前缓存参数和this
    // 提前缓存参数和this
    var slice = Array.prototype.slice;
    Function.prototype.mybind = function (asThis) {
        // 1、第一个参数是this, 后边的参数才是额外的参数,所以要对参数进行一个截取
        // 2、因为arguments是一个伪数组,所以没有数组的方法,
        //    所以可以提前获取下数组的的方法slice
        var cachedArgs = slice.call(arguments, 1);
        console.log('mybind.....', cachedArgs) // [1, 2]
        // 3、最后它是要返回一个新的函数,所以这里先定义一个要返回的函数
        var innerFn = function () {
            ///4、这里要先汇总一下新函数传过来的参数和提前缓存的参数
            var args = slice.call(arguments);
            cachedArgs = cachedArgs.concat(args);
            console.log('cachedArgs::', cachedArgs) // [1, 2, 3, 4]
            console.log('asThis::', asThis) // '我是this'
        };
        return innerFn;
    }

    function fn() {

    }
    var newFn = fn.mybind('我是this', 1, 2);
    newFn(3, 4);

这里对slice.call(arguments, 1)这行做一个说明:以为这里的slice是一个纯净的方法,是没有数据的。所以他要slice就要根据this去slice,所以这里就要把要截取的数组arguments当成它的this,这样就截取到了除第一个参数的外的额外参数如1和2.

3.下边就是随着newFn方法的调用,要这个方法可以执行起来,其实就是要改变this的这个方法fn要执行起来,这就要思考怎么在innerFn的里边拿到fn这个方法。
    var slice = Array.prototype.slice;
    Function.prototype.mybind = function (asThis) {
        // 1、第一个参数是this, 后边的参数才是额外的参数,所以要对参数进行一个截取
        ///2、因为arguments是一个伪数组,所以没有数组的方法,
        //    所以可以提前获取下数组的的方法slice
        var cachedArgs = slice.call(arguments, 1);
        console.log('mybind.....', cachedArgs) // [1, 2]
        // 3、最后它是要返回一个新的函数,所以这里先定义一个要返回的函数

        // 5、① 这里保存fn的值
        var callFn = this;
        var innerFn = function () {
            ///4、这里要先汇总一下新函数传过来的参数和提前缓存的参数
            var args = slice.call(arguments);
            cachedArgs = cachedArgs.concat(args);
            console.log('cachedArgs::', cachedArgs) // [1, 2, 3, 4]
            console.log('asThis::', asThis) // '我是this'

            // 5、② 用fn 改变this,传递参数
            // 原函数 改变this 参数
            // 这里return 是因为要可以拿到newFn 的返回值
            return callFn.apply(asThis, cachedArgs);

        };
        return innerFn;
    }

    function fn() {
        console.log('this::', this)
        console.log('arguments::', arguments)
        return 'fn的返回值'
    }
    var newFn = fn.mybind('我是this', 1, 2);
    console.log(newFn(3, 4)); // ''fn的返回值''
4.要求返回的函数可以被new(第6、7步)
 var slice = Array.prototype.slice;
    Function.prototype.mybind = function (asThis) {
        // 1、第一个参数是this, 后边的参数才是额外的参数,所以要对参数进行一个截取
        ///2、因为arguments是一个伪数组,所以没有数组的方法,
        //    所以可以提前获取下数组的的方法slice
        var cachedArgs = slice.call(arguments, 1);
        console.log('mybind.....', cachedArgs) // [1, 2]
        // 3、最后它是要返回一个新的函数,所以这里先定义一个要返回的函数

        // 5、① 这里保存fn的值
        var callFn = this;
        var innerFn = function () {
            ///4、这里要先汇总一下新函数传过来的参数和提前缓存的参数
            var args = slice.call(arguments);
            cachedArgs = cachedArgs.concat(args);
            console.log('cachedArgs::', cachedArgs) // [1, 2, 3, 4]
            console.log('asThis::', asThis) // '我是this'

            console.log('查看调用的this:', this); //这里可以看到被调用时是Window 被new时是innerFn {}
            // 所以我们就可以通过this instanceof innerFn来判断是否是被new的
            // 6、这里区分是new的还是调用?
            if (this instanceof innerFn) {
                // 7、这里模拟创建对象的4步曲
                var target = {}; //创建一个空对象
                // 原型挂载
                target.__proto__ = callFn.prototype;
                // 执行构造函数
                callFn.apply(target, cachedArgs);
                return target;
            } else {
                // 5、② 用fn 改变this,传递参数
                //     原函数 改变this 参数
                //     这里return 是因为要可以拿到newFn 的返回值
                return callFn.apply(asThis, cachedArgs);
            }

        };
        return innerFn;
    }

    function fn() {
        this.tag = 'Green';
        console.log('this::', this)
        console.log('arguments::', arguments)
        return 'fn的返回值'
    }
    var newFn = fn.mybind('我是this', 1, 2);
    console.log('被调用::', newFn(3, 4)); // 'fn的返回值'
    // 通过上边的打印可以看出fn() this是window new Xx 就是Xx的实例

    // 要求返回的函数可以被new
    var fnObj = fn.mybind('new的this', 5, 6);
    var instance = new fnObj(7, 8);
    console.log('被new::', instance); // fn {tag: 'Green'}
5. 以上就完成了整个功能,下边就展示下完成代码:

这里再加个补充;我们在调用mybind时前边对象会被改变的,所以要确保它是个函数,否则告知要传一个函数

var slice = Array.prototype.slice;
Function.prototype.mybind = function (asThis) {
    var cachedArgs = slice.call(arguments, 1);
    var callFn = this;
    if(typeof callFn !== 'function') throw new Error('当前实例非函数')
    var innerFn = function () {
        var args = slice.call(arguments);
        cachedArgs = cachedArgs.concat(args);
        // 区分是否被new
        // 这里可以分别打印下被调用和被new时this的区别
        if (this instanceof innerFn) {
            var target = {}; 
            target.__proto__ = callFn.prototype;
            callFn.apply(target, cachedArgs);
            return target;
        } else {
            return callFn.apply(asThis, cachedArgs);
        }
    };
    return innerFn;
}

function fn() {
    this.tag = 'ABC';
    return 'fn的返回值'
}
// 被调用时
var newFn = fn.mybind('我是this', 1, 2);
console.log('被调用::', newFn(3, 4)); // 'fn的返回值'

// 被new时
var fnObj = fn.mybind('new的this', 5, 6);
var instance = new fnObj(7, 8);
console.log('被new::', instance); // fn {tag: 'ABC'}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 29天前 0

暂无评论

推荐阅读
  mQa6OV8cozXc   22天前   25   0   0 JavaScript
  W0JYIGaysMAv   24天前   20   0   0 JavaScript
  Sb0Lu6UKRwVp   18天前   21   0   0 JavaScript
  X1N8l2v9m1kd   23天前   20   0   0 JavaScript
X1N8l2v9m1kd
作者其他文章 更多

2024-04-13

2024-04-07