为什么这里的this是指向windows

co(function *() {
            var now = Date.now();
            yield sleep200;
            console.log(Date.now() - now);
        });

        function co(fn){
            var gen = fn();
            next();
            function next(res){
                var ret;
                ret = gen.next(res);
                // 全部结束
                if(ret.done){
                    return;
                }
                // 执行回调
                if (typeof ret.value == 'function') {
                    ret.value(function(){
                        next.apply(this, arguments);
                    });
                    return;
                }
                throw 'yield target no supported!';
            }
        }

        function sleep200(cb){
            setTimeout(cb, 200)
        }

在next.apply()那一行。
我这里有点糊涂了,像这种点调用的话,this不应该指向调用者吗?也就是next对象,可这里next是个函数。可为什么是window对象呢

阅读 4.5k
5 个回答
ret.value(function(){
    next.apply(this, arguments);
});
这里ret.value的参数是一个匿名函数,你见过匿名函数中的this不是window的情况吗?

这个 this 是在 next 函数中,而不是在 next.apply 的apply 中。
next 函数的调用是 next() 所以其中的 this 是 window。
http://zonxin.github.io/post/...

你在哪里打印的this?
如果co这个函数,直接执行,相当于window.co();this当然是window

这段代码好绕,脑壳都被绕晕了

关键在这里

function() {
    next.apply(this, arguments);
});

这个函数是作为参数被传入 sleep200(cb) 的,也就是 setTimeout(cb, 200) 这句话里的 cb 这个参数。

很明显,在 setTimeout 到时间之后执行 cb() 绝不是 xxxx.cb() 这种方式执行,而是 cb() 这样执行,所以,cb() 里面的 this 指向全局对象,也就是 window

方法调用和函数调用

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