js实现call、apply、bind函数

  • 手写call函数
            let person = {
                name: 'lisi',
                getName() {
                    return this.name;
                }
            }
            let obj = {
                name: '张三'
            }
            // 在函数原型上添加自定义mycall函数
            Function.prototype.myCall = function(context){
                // this 哪个方法调用指向这个方法
                // console.log(this)
                if(typeof this !== 'function') {
                    throw new Error(`${this} is not a function}`
                }
                // context 可能传null,undefined, ''
                context = context || window
                // 获取参数,除了第一个
                let arg = [...arguments].slice(1);
                // 传过来的this上添加一个调用的方法,后面调用后删除
                context.fn = this;
                // 把参数传进去后调用,把调用结果返回出去,后删除context上的fn方法
                let result = context.fn(...arg);
                delete context.fn;
                return result;

            }
            let name = person.getName.myCall(obj);
            console.log(name)

  • 手写apply函数
    Function.prototype.myApply = function(context) {
        // this 指向调用的方法
        if(typeof this !== 'function') {
            throw new Error(`${this} is not a function}`
        }
        context = context || window;
        context.fn = this;
        let result;
        // arguments[1] 参数数组
        if(arguments[1]) {
            result = context.fn(...arguments[1])
        }else {
            result = context.fn()
        }
        delete context.fn;
        return result;
    }
  • 手写bind函数
    Fucntion.prototype.myBind = function(context) {
        if(typeof this !== 'function') {
            throw new Error(`${this} is not a function}`
        }
        context = context || window;
        context.fn = this;
        // 获取参数
        let args = [...arguments].slice(1);
        return () => {
            return context.fn.apply(context, [...args])
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容