zoukankan      html  css  js  c++  java
  • 实现一个call或 apply

    引荐来源:JavaScript深入之call和apply的模拟实现 #11

    call 定义:

      fn.call(thisarg,arg1,arg2,...) 调用一个函数, 其具有一个指定的this值和分别地提供的参数

    call 核心:

      1、将函数设为对象的属性

      2、执行&删除这个函数

      3、指定this到函数并传入给定参数执行函数

      4、如果不传入参数,默认指向为 window

    首先来一个比较简单的call实现方法:

    var foo = {
        value: 1,
        bar: function() {
            console.log(this.value)
        }
    }
    foo.bar() // 1  这里的this虽然指向了foo确给foo添加了一个属性,这不是我们希望得到的结果

    我们接着往下面看:

    Function.prototype.call2 = function(content = window) {
        content.fn = this;
        let args = [...arguments].slice(1);
        let result = content.fn(...args);
        delete content.fn;
        return result;
    }
    let foo = {
        value: 1
    }
    function bar(name, age) {
        console.log(name)
        console.log(age)
        console.log(this.value);
    }
    bar.call2(foo, 'blue', '18') // blue 18 1  完美实现了call的方法是不是很开心呀

    apply 定义

      fn.apply(thisarg,[argsarray])  调用一个函数,以及作为一个数组(或者类数组对象)提供的参数

    apply跟call的实现方法大同小异  只是参数形式有所不同

    Function.prototype.apply2 = function(context = window) {
        context.fn = this
        let result;
        // 判断是否有第二个参数
        if(arguments[1]) {
            result = context.fn(...arguments[1])
        } else {
            result = context.fn()
        }
        delete context.fn
        return result
    }

      

      

  • 相关阅读:
    車(rook)
    那些年,我们学过的文化课
    皇后(queen)
    蚂蚁运输(ant)
    [Z]CS权威会议
    [Z] 北大一牛人生物转申CS的经历
    TLS协议扫盲(握手,非对称加密,证书,电子签名等)
    关于SSE的一些资料
    Java下LDAP操作的资料
    [Z] Windbg以及vs debug使用
  • 原文地址:https://www.cnblogs.com/wuconghui/p/10973647.html
Copyright © 2011-2022 走看看