首页 > 其他分享 >手写bind

手写bind

时间:2024-04-07 12:33:42浏览次数:14  
标签:cachedArgs console log bind slice var 手写 fn

首先写一个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. 以上就完成了整个功能,下边就展示下完成代码:
 var slice = Array.prototype.slice;
    Function.prototype.mybind = function (asThis) {
        var cachedArgs = slice.call(arguments, 1);
        var callFn = this;
        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'}

标签:cachedArgs,console,log,bind,slice,var,手写,fn
From: https://www.cnblogs.com/lvkehao/p/18118755

相关文章

  • Android Binder——Java服务注册(九)
           对于Java端使用Binder服务,主要就是注册服务和获取服务,入口都是通过ServiceManager.java中的对应方法实现。这里我们就先介绍一下Java注册Binder服务的流程。一、ServiceManager代理       无论是ServiceManager.addService()还是Service......
  • 2.手写JavaScript广度和深度优先遍历二叉树
    一、核心思想:1.深度遍历:依靠栈先进后出的机制,分别设置返回结果的数组和栈数组,首先判断栈非空,对每个结点,将其出栈并把值push到结果数组,判断是否有右左孩子,分别将其加入栈中,循环执行上述操作。否则返回结果数组。2.广度遍历:依靠队列先进先出的机制,分别设置返回结果的数组和队......
  • 【CANN训练营笔记】OrangePI AIPro 体验手写体识别模型训练与推理
    CANN简介当我们谈到香橙派AIPro的时候,总会把她和昇腾生态关联起来,因为在昇腾芯片的加持下,这款开发板有着出色的算力,被众多开发者追捧。而谈到昇腾芯片,我们不得不提上层的AI异构计算架构CANN。异构计算架构CANN(ComputeArchitectureforNeuralNetworks)是华为针对AI场......
  • 基于深度学习的手写数字和符号识别系统(网页版+YOLOv8/v7/v6/v5代码+训练数据集)
    摘要:在本篇博客中,我们深入研究了基于YOLOv8/v7/v6/v5的手写数字和符号识别系统。本系统的核心采用了YOLOv8技术,并整合了YOLOv7、YOLOv6、YOLOv5算法来进行性能指标的对比分析。我们详细地回顾了国内外在手写数字和符号识别领域的研究现状,并对使用到的数据集处理方法、算法原理、模......
  • 手写Promise
    1.建立基础的构造函数需求基于Promises/A+(promisesaplus.com),我们需要实现:promise有三个状态:pending(未完成),fulfilled(完成),orrejected(拒绝)。初始状态为pending,且状态结束只能从pending改为fulfilled或者rejected,promise的状态改变为单向且不可逆。promise接......
  • 【JS】手写Promise.all
    注意判断参数是否为空时,不能只根据length判断,因为只要是可迭代对象都可以用length。js有哪些内置可迭代对象可以看另一篇文章:JS内置可迭代对象。如何变为可迭代对象可以看其他两篇文章:Object.definePropery和使如下代码成立:var[a,b]={a:1,b:2}防止用户传入非P......
  • 手写防抖节流
    防抖持续频繁触发某个机制,则需要等待指定的时间再执行。/**手写防抖*用法:函数在n秒后再执行,如果n秒内被触发,重新计时,保证最后一次触发事件n秒后才执行。*思路:*1、保存一个变量timer*2、返回一个闭包函数函数内判断一下timer是否有值*2.1、如果有......
  • vue3 手机端 手写签字
    <template><div><div><canvasclass="canvas"id="canvas"ref="canvas"></canvas><canvasid="blank"style="display:none"></canvas><p......
  • 为什么 InputComponent->BindAxis(TEXT("ViewHorizontalOffSet"),this,&AMarioControl
    在UnrealEngine中,InputComponent->BindAxis和事件绑定(如OnComponentBeginOverlap)使用不同的系统和要求。这些差异导致了在绑定函数时对UFUNCTION()宏的不同需求。BindAxis和UFUNCTION()宏BindAxis:用于绑定输入轴(如游戏手柄的移动或旋转)。当绑定轴输入时,BindAxis函数直接引用......
  • 手写数字图片识别——DL 入门案例
    DeepLearningDemoofPrimary下面介绍一个入门案例,如何使用TensorFlow和Keras构建一个CNN模型进行手写数字识别,以及如何使用该模型对自己的图像进行预测。尽管这是一个相对简单的任务,但它涵盖了深度学习基本流程,包括:数据准备模型构建模型训练模型预测输入:importtenso......