zoukankan      html  css  js  c++  java
  • 原生JS模拟实现call、apply、bind

    function call_mock (obj) {
        var aim_fun = this;
        var argument = [];
        for (var i = 1; i < arguments.length; i++) {
            argument.push(arguments[i]);
        }
        obj.aim_fun = aim_fun;
        var result = eval('obj.aim_fun('+ argument.join() + ')');
        delete obj.aim_fun;
        return result;
    }
    
    Function.prototype.call_mock = call_mock;
    
    function apply_mock (obj, args) {
        var aim_fun = this;
        obj.aim_fun = aim_fun;
        var result = eval('obj.aim_fun('+ args.join() + ')');
        delete obj.aim_fun;
        return result;
    }
    
    Function.prototype.apply_mock = apply_mock;
    
    function bind_mock (obj) {
        var aim_fun = this;
        var argument = [];
        for (var i = 1; i < arguments.length; i++) {
            argument.push(arguments[i]);
        }
        var fNOP = function () {};
        var fBound = function () {
            return aim_fun.apply_mock(obj, argument)
        }
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
    }
    
    Function.prototype.bind_mock = bind_mock;
    
    var a = {
        c:1,
        see(a, b) {
            console.log(`${this.c}${a}${b}`);
        }
    }
    
    c = 0;
    
    a.see.bind_mock(global, 1, 2);
  • 相关阅读:
    前缀和
    hdu6290奢侈的旅行
    make_pair
    New Year and Buggy Bot
    STL next_permutation 算法原理和自行实现
    前端面试题集合
    node设置cookie
    黑客与geek
    xss
    node async
  • 原文地址:https://www.cnblogs.com/xcxjy/p/10441142.html
Copyright © 2011-2022 走看看