求解一道关于call的题目

fn2.num 为啥打印的是111,f1中的this经过call指向了f2,为啥去打印f1的num?

function fn1() {
    console.log(1);
    this.num = 111;
    this.sayHey = function() {
        console.log("say hey.");
    }
}
function fn2() {
    console.log(2);
    this.num = 222;
    this.sayHello = function() {
        console.log("say hello.");
    }
}

fn1.call(fn2);

console.log(fn2.num); // 111
阅读 1.6k
2 个回答

fn1.call(fn2),执行的程序是fn1的内容,但this是fn2,所以相当于执行了下面的代码,也就是fn1里面的this替换为fn2

console.log(1);
fn2.num = 111;
fn2.sayHey = function() {
    console.log("say hey.");
}

显然, console.log(fn2.num)输出111

f1中的this经过call指向了f2,那么在f1中的this就是f2,执行代码

this.num = 111;

的时候也就是

f2.num = 111;

所以最后会输出111

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题