fn1callcallfn2

25次阅读

共计 844 个字符,预计需要花费 3 分钟才能阅读完成。

描述

function fn1(){console.log(1);
}
function fn2(){console.log(2);
}
fn1.call(fn2); // 输出 1
fn1.call.call(fn2); // 输出 2 

问题

看到这个题目,第一反应是蒙圈的。

fn1.call(fn2); 这个是理解的。
fn1.call.call(fn2);这个蒙圈了。

理解

有些绕,需要多念叨念叨琢磨琢磨。

call 方法是 Function.prototype 原型上天生自带的方法,所有的函数都可以调用的。

我觉得 call方法本身没有具体 return 什么出来,所以是undefined

Function.prototype.call=function call(context){// [native code]
    // call 方法的功能
    // 1. 把指定函数中的 this 指向 context
    // 2. 把指定函数执行
    
    // 那么 call 方法中的 this,即为指定函数。也就是说
    // 1. 把 this 中 的 this 关键字指向 context;
    // 2. 把指定函数执行 this();};

fn1.call(fn2);

按照上面的理解

  1. call 方法中的 this 是 fn1
  2. 把 call 方法中的 this(fn1)中的 this 指向 fn2
  3. 调用 call 方法中的 this

所以调用的是 fn1,此时 fn1 中的 this 指向的是 fn2。
但是这个方法里面并没有使用 this,而是直接输出了 1。

fn1.call.call(fn2);

按照上面的理解

  1. call 方法中的 this 是 fn1.call【所有函数都可以调用 call,调用的是原型上 call 方法】
  2. 把 call 方法中的 this (fn1.call) 中的 this 指向 fn2
  3. 调用 call 方法中的 this

所以调用的是 fn2(这里有些绕,多念叨念叨琢磨琢磨),此时 fn1.call 中的 this 指向的是 fn2。
它改变了 call 方法(Function.prototype 原型上的 call)的 this 指向。
此处调用了 call 方法中的 this,即调用了 fn2,输出了 2。

正文完
 0