zoukankan      html  css  js  c++  java
  • 手写一个call、apply、bind

    一 写前需要先了解一下他们的用法

    call 和 apply 是为了动态改变 this 而出现的.传入call的参数只能是单个参数,不能是数组。apply可传入数组。

    区别

    func.call(this, arg1, arg2);
    func.apply(this, [arg1, arg2])

    call

        Function.prototype.call1 = function (context) {
            var context = context || window;
            context.fn = this
            let args = [...arguments].slice(1)
            let result = context.fn(...args)
            delete context.fn
            return result
        }

    apply

        Function.prototype.apply1 = function (context) {
            var context = context || window;
            context.fn = this;
            let args = arguments[1]
            let result;
            if (args) {
                result = context.fn(...args)
            } else {
                result = context.fn()
            }
            delete context.fn
            return result
        }

    bind

    暂无

    测试

        var name = '呵呵'
        var foo = {
            name: '嘿嘿',
        }
    
        function bar(a, b, c) {
            return {
                name: this.name,
                a,
                b,
                c
            }
        }
    
        console.log(bar.call1(foo, 11, 12, 13))
        console.log(bar.apply1(foo, [11, 12, 13]))
        console.log(bar.bind1(foo, 11))
  • 相关阅读:
    twfont
    判断数组中某个元素的个数
    vue swiper中的大坑
    this指向问题
    vue.nextTick简单的用法
    类图解析
    设计模式
    设计模式
    Http Notes
    VS Notes
  • 原文地址:https://www.cnblogs.com/gaoht/p/12745518.html
Copyright © 2011-2022 走看看