美文网首页js
javascript中的call

javascript中的call

作者: CRUD_科科 | 来源:发表于2019-06-24 13:44 被阅读0次
    // call 的特点
    // 1)可以改变当前函数的this指向
    // 2)还会让当前函数执行
    // 3)第一个参数改变当前参数的this,后面的参数在当前参数的arguments获取
    
    // function fn1() {
    //   console.log(this,arguments)
    // }
    // fn1.call('hello',1,2,3,4)
    // function fn1() {
    //   console.log(1)
    // }
    // function fn2() {
    //   console.log(2)
    // }
    // fn1.call.call.call(fn2)  // 2 执行了fn2
    
    Function.prototype.call = function (context) {
      context = context ? Object(context) : window;
      context.fn = this;   // 让传入的this.fn执行,相当于fn的this指向的是.前面的,也就是传入的this
      let args = [];
      for (let i = 1; i < arguments.length; i++) {
        args.push('arguments[' + [i] + ']')
      }  // args = ["arguments[1]","arguments[2],"arguments[3]""]
      let r = eval('context.fn(' + args + ')');
      delete context.fn;
      return r
    }
    function fn1() {
      console.log(1)
    }
    function fn2() {
      console.log(2)
    }
    fn1.call('hello', 1, 2, 3, 4, 5);
    fn1.call.call.call(fn2);
    

    相关文章

      网友评论

        本文标题:javascript中的call

        本文链接:https://www.haomeiwen.com/subject/kvgnqctx.html