zoukankan      html  css  js  c++  java
  • call,apply,bind实现

    自定义call方法

    Function.prototype.myCall = function (context) {
        if (typeof this !== 'function'){
            throw new TypeError(`${context} is not a function`)
        }
        context = context || window
        context.fn = this
        let args = [...arguments].slice(1)
        let myfn = context.fn(args)
        delete context.fn
        return myfn
    }

    自定义apply方法

    Function.prototype.myApply = function (context) {
        if (typeof this !== 'function'){
            throw new TypeError(`${context} is not a function`)
        }
        context = context || window
        context.fn = this
        let myfn
        if (arguments[1]) {
            myfn = context.fn(...arguments[1])
        } else {
            myfn = context.fn()
        }
        delete context.fn
        return myfn
    }

    自定义bind方法

    Function.prototype.myBind = function (context) {
        if (typeof this !== 'function'){
            throw new TypeError(`${context} is not a function`)
        }
        const _this = this
        const args = [...arguments].slice(1)
        return function myFn () {
            if (this instanceof myFn) {
                return new _this(...args, ...arguments)
            }
            return _this.apply(context, args.concat(...arguments))
        }
    }

    参考:

    https://juejin.cn/post/6844903764999012366#heading-2

  • 相关阅读:
    DIV+CSS中的滤镜和模糊
    初识DIV+CSS
    HTML核心标签之表格标签(二)
    HTML核心标签之表格标签(一)
    关于HTML的两个实例
    CSS的四种引入方式
    HTML中的表单
    HTML基础知识概括
    python3操作socketserver
    数据库MySQL的基本操作
  • 原文地址:https://www.cnblogs.com/dropInInt/p/15219655.html
Copyright © 2011-2022 走看看