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    
  • 相关阅读:
    linux下清空文件的几种方式以及对比
    远程桌面连接无法验证您希望连接的计算机的身份-mac连接远程桌面
    Linux配置临时IP和网关命令
    linux(centos、ubuntu)网卡配置文件不生效
    负载均衡
    Zookeeper基础使用机制原理
    高性能RPC框架选型
    事务隔离机制
    一致性协议Raft
    机器学习入门
  • 原文地址:https://www.cnblogs.com/xiaokeai0110/p/14045267.html
Copyright © 2011-2022 走看看