zoukankan      html  css  js  c++  java
  • apply,call,bind方法简单实现

    apply方法:在传入的this对象中创建函数,以实现在this环境中执行函数的功能。

    let func1 = {
        name: 'test'
    }
    let func2 = function (a, b, c) {
        return a + b + c + this.name;
    }
    
    Function.prototype.myApply = function (thisArg, argArr) {
        thisArg = thisArg ? Object(thisArg) : window;
        thisArg.func = this;
        let result = thisArg.func(...argArr);
        delete thisArg.func;
        return result;
    }
    
    func2.myApply(func1, ['1', '2', '3']);       //123test

    call方法:同上,参数传入方式不同。

    let func1 = {
        name: 'test'
    }
    let func2 = function (a, b, c) {
        return a + b + c + this.name;
    }
    
    Function.prototype.myCall = function (thisArg, ...argArr) {
        thisArg = thisArg ? Object(thisArg) : window;
        thisArg.func = this;
        let result = thisArg.func(...argArr);
        delete thisArg.func;
        return result;
    }
    
    func2.myCall(func1, '1', '2', '3');       //123test

    bind方法:返回的是一个函数,而不是运行结果,并且注意继承和实例问题。

    let func1 = {
        name: 'test'
    }
    let func2 = function (a, b, c) {
        return a + b + c + this.name;
    }
    
    Function.prototype.myBind = function (thisArg, ...argArr) {
        let self = this;
    
        let Bound = function (...args) {
            //如果当前为bound的实例,直接使用bound的this
            let thisAgr = this instanceof Bound ? this : self;
    
            return self.apply(thisAgr, [...argArr, ...args]);
        }
    
        //为了可以找到目标函数,即func2的原型中的属性和方法,继承当前函数的原型链方法
        Bound.prototype = Object.create(self.prototype);
        Bound.prototype.constructor = self;
    
        return bound;
    }
    
    func2.myBind(func1, '1', '2', '3')();       //123test    
  • 相关阅读:
    spring 注解笔记
    spring boot 拦截器
    spring boot 启动流程及其原理
    Spring之BeanFactory和FactoryBean接口的区别
    微信支付
    三级联动
    搜索分页
    多选标签
    分类界面 大分类小分类
    触底下拉
  • 原文地址:https://www.cnblogs.com/xiaokeai0110/p/14045267.html
Copyright © 2011-2022 走看看