javascript - arguments.callee递归中的this值是?
怪我咯
怪我咯 2017-04-10 17:08:01
[JavaScript讨论组]
//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。不知是否理解正确。

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
大家讲道理
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是不同的~~

PHPz

直接使用call()调用不就可以吗?

var foo = function (bar) {
    if (!bar) { return arguments.callee.call(window,true); }
    console.log(this);      // window对象
}
foo();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号