zoukankan      html  css  js  c++  java
  • 手写call、apply、bind方法

    // call 
    Function.prototype.call = function (context, ...args) {
        context = context || window
        const fnSymbo = Symbol('fn')
        context[fnSymbo] = this
        let fn = context[fnSymbo](...args)
    
        delete context[fnSymbo]
    
        return fn
    }
    
    var obj = { name: 'cedric' }
    
    function fn(age, address) {
        console.log(`${this.name} is ${age},in ${address}`)
    }
    
    fn.call(obj, 29, '上海')  // cedric is 29,in 上海
    
    // apply 
    Function.prototype.apply = function (context, argsArr) {
        context = context || window;
    
        const fnSymbol = Symbol("fn");
        context[fnSymbol] = this;
    
        let fn = context[fnSymbol](...argsArr);
        delete context[fnSymbol];
        return fn
    }
    
    var obj = { name: 'cedric' }
    
    function fn(age, address) {
        console.log(`${this.name} is ${age},in ${address}`)
    }
    
    fn.apply(obj, [29, '上海'])  // cedric is 29,in 上海
    
    // bind
    Function.prototype.bind = function (context, ...args) {
        context = context || window;
        const fnSymbol = Symbol("fn");
        context[fnSymbol] = this;
    
        return function (..._args) {
            args = args.concat(_args);
    
            context[fnSymbol](...args);
            delete context[fnSymbol];
        }
    }
    
    var obj = { name: 'cedric' }
    
    function fn(age, address) {
        console.log(`${this.name} is ${age},in ${address}`)
    }
    
    fn.bind(obj, 29, '上海')()  // cedric is 29,in 上海
    
  • 相关阅读:
    Noip2012 开车旅行
    「NOI2018」归程
    2019.10.30 队测(晚上)
    洛谷P1138 第k小整数
    洛谷P2870 [USACO07DEC]最佳牛线,黄金Best Cow Line, Gold
    Noip-pj2018游记
    洛谷P4994 终于结束的起点
    《退役的你》
    《膜你抄》
    洛谷P5087 数学
  • 原文地址:https://www.cnblogs.com/cckui/p/14636306.html
Copyright © 2011-2022 走看看