zoukankan      html  css  js  c++  java
  • 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)
            }
        }
    }
  • 相关阅读:
    对象的方法
    uni-app运行
    flex取值
    阿里矢量库使用
    移动端vue项目模板
    微信分享--转载
    页面流动条
    uni-app打包
    Hibernate~DAO
    EL表达式
  • 原文地址:https://www.cnblogs.com/kevin-ye/p/3620503.html
Copyright © 2011-2022 走看看