原生JS实现 call apply bind

call apply bind 的 作用

都是用来改变this的指向,在平时工作过程中,除了实现对象的继承,在写一些基础类,或者公用库方法的时候会用到它们,其他时候 call 和 apply 的应用场景并不多。
在React中bind常用来绑定事件,改变this的指向

call apply bind 的 区别

  1. call apply方法都是在调用之后立即执行的,而bind是返回原函数,需要再调用一次才能执行
  2. 传参方式的区别
var newFn1 = fn1.bind(newObj,arg1,arg2....); 

bind 第一个参数为需改变的新指向,之后的参数以,隔开
如需调用该函数,需要再次调用 newFn1 方法

fn2.call(newObj,arg1,arg2....)

无须再次调用,调用call函数即立即执行

fn3.apply(newObj,[arg1,arg2]....)

第一个参数仍是newObj,但是之后的参数需要放在数组中,传入apply方法中,并且调用apply方法即立即执行

使用原生JS实现call aply bind 方法

实现call 方法

    Function.prototype.nyCall = function(context){
        if(typeof this != 'function'){
            throw new TypeError('Error')
        } //判断调用该方法的是不是函数,如果不是,则抛出异常
        if(context === null || context === undefined){
            context = window //指定为null 和 undefined 的 this值会自动指向全局对象(浏览器中为windiw)
        } else {
            context = Object(context) //值为数字,字符串,布尔值等的this 会指向原始值的实例对象
        }
        context.fn = this
        // 通过参数伪数组将context后面的参数取出来
        let args = [...arguments].slice(1)
        // 调用该函数
        let result = context.fn(...args);
        // 删除fn
        delete context.fn
        // 返回结果
        return result
    }

实现apply

    Function.prototype.myApply = function (context) {
        if (typeof this !== 'function') {
            throw new TypeError('Error')
        }
        //判断调用该方法的是不是函数,如果不是,则抛出异常
        if (context === null || context === undefined) {
            context = window     // 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中为window)
        } else {
            context = Object(context) // 值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的实例对象
        }
        context.fn = this
        var  result = null 
        //判断是否存在第二个参数
        //如果存在就将第二个参数也展开
        // 如果不存在直接调用该方法
        if(arguments[1]) {
            result = context.fn(...arguments[1])
        } else {
            result = context.fn()
        }
        delete context.fn
        return result
    }

实现bind

Function.prototype.mybind = function (context) {
        if (typeof this !== 'function') {
            throw new TypeError('Error')
        }
        const _this = this
        // 取参数 
        const args = [...arguments].slice(1)
        //返回一个改变了this指向的新的函数
        return function F () {
            if (this instanceof F) { // this是否是F的实例 也就是返回的F是否通过new调用
                return new _this(...args, ...arguments)
            }
            return _this.apply(context,args.concat(...arguments))
        }
    }
发布了2 篇原创文章 · 获赞 9 · 访问量 49

猜你喜欢

转载自blog.csdn.net/qq_37278704/article/details/104416143