setTimeout里面this指向问题

var test = {
    info: "hello",
    fn: function(){
        console.log(this.info);
        setTimeout(arguments.callee, 1000)
    }
}

运行上面的test.fn()的时候。。第一次是可以返回"hello"的。第二次之后就返回"undefined"了,把console.log(this.info)改成console.log(this)可以发现,原因是setTimeout里面的this在第二次以后都变成指向window了。。我们的目的是让this指向test。搜了一下资料。找出一个解决方法:

var test = {
    info: "hello",
    fn: function(){
        console.log(this.info);
        setTimeout(this.bind(this, arguments.callee), 1000);
    },
    bind: function(object, func){
        return function(){
            return func.apply(object, arguments)
        }
    }
}

 

posted @ 2014-03-24 11:38  KEVIN_葉  阅读(273)  评论(0编辑  收藏  举报