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 上海
    
  • 相关阅读:
    [状压DP][二分]JZOJ 3521 道路覆盖
    字符串操作
    练习: 判断一个数是否为小数
    Python 深浅拷贝
    编码
    python中的 == 和 is 的区别
    Python3 字典的增删改查
    Python3 列表的基本操作
    初识 Python
    方法的入门
  • 原文地址:https://www.cnblogs.com/cckui/p/14636306.html
Copyright © 2011-2022 走看看