javascript - 为什么这里的this是指向windows
本文介绍了javascript - 为什么这里的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对象呢
解决方案
ret.value(function(){
next.apply(this, arguments);
});
这里ret.value的参数是一个匿名函数,你见过匿名函数中的this不是window的情况吗?
这篇关于javascript - 为什么这里的this是指向windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文