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对象呢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这个 this 是在 next 函数中,而不是在
next.apply的apply 中。next 函数的调用是
next()所以其中的this是 window。http://zonxin.github.io/post/...
你在哪里打印的this?
如果co这个函数,直接执行,相当于window.co();this当然是window
这段代码好绕,脑壳都被绕晕了
关键在这里
这个函数是作为参数被传入
sleep200(cb)的,也就是setTimeout(cb, 200)这句话里的cb这个参数。很明显,在
setTimeout到时间之后执行cb()绝不是xxxx.cb()这种方式执行,而是cb()这样执行,所以,cb()里面的this指向全局对象,也就是window方法调用和函数调用