首页 > arguments.callee递归中的this值是?

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是不同的~~

【热门文章】
【热门文章】