javascript - arguments.callee递归中的this值是?

查看:126
本文介绍了javascript - arguments.callee递归中的this值是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

//case 1
var foo = function (bar) {
    if (!bar) { return arguments.callee(true); }
    console.log(this);      // not global
}
foo();

//case 2
var foo = function x(bar) {
    if (!bar) { return x(true); }
    console.log(this);      // global
}
foo();

//case 3
(function foo(bar) {
    if (!bar) { return foo(true); }
    console.log(this);     // global
})();                               

抱歉,本不想问这种烂大街型问题。但是,case 1这种情况,在dmitrysoshnikov那篇文章里,也没提到。按那篇文章说法,case1的(左边,不正是引用类型吗?那this应该基于base、指向global啊……

case 2和3,我也认为是global,但可能是歪打正着:case2的foo是引用类型,其base为global,所以this指向global。而case 3的(左边不是引用类型,所以this是null,在no strict模式下指向global。不知是否理解正确。

解决方案

var foo = function (bar) {
    if (!bar) { return arguments.callee(true); }
    console.log(this);      // arguments对象
}
foo();

callee作为arguments的一个属性,指向当前执行的函数对象
arguments.callee(true);方式调用时,callee指向的函数对象作为arguments的一个方法被调用,此时的this为arguments对象

如果写成这样:

var foo = function (bar) {
    var tempFun;
    if (!bar) { 
        tempFun=arguments.callee;
        return tempFun(true);
    }
    console.log(this);      //输出global对象
}
foo();

一个函数作为一个对象方法调用和作为普通函数调用指向的this是不同的~~

这篇关于javascript - arguments.callee递归中的this值是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆