js 作用域的问题

dom:

<view :animation="barr.animationIndex" v-for="(barr,index) in dataBarrage" :key="index">{{barr.value}}</view>

js:

    var _this = this;

    for (let i = 0; i < _this.dataBarrage.length; i++) {
        var num = Math.random(); //生成随机数
        var item = _this.dataBarrage[i];
        _this.$set(item, 'x', _this.windowWidth + 200 * num);
        _this.$set(item, 'y', num * 100 + 30);
        _this.$set(item, 'animationIndex', 'animationAll' + i); //存变量名
        //先移到窗口外面的固定位置
        _this.animation.translate(item.x, item.y).step({ duration: 10 });
        item.animationIndex = _this.animation.export();     //第一次赋值
                
        setTimeout(function() {                    
           _this.animation.translate(-_this.windowWidth - 300, item.y).step();
           item.animationIndex = _this.animation.export();
        }.bind(_this),1000);
    }

我在setTimeout函数里面给item.animationIndex赋值,为什么只有最后一个值生效,前面的 item.animationIndex第一次赋值都是循环后的结果都是正确的,在setTimeout函数里面的时候,给item.animationIndex赋值就只有最后一个生效,是怎么回事呢。应该怎么写呢?

阅读 1.8k
3 个回答
let item = _this.dataBarrage[i];

你的这个item不是一个局部变量相当于在for循环外声明 每次赋值都是覆盖 导致最后执行setTimeout里函数执行的时候读取的是最后一此覆盖的值

(function(item){
  setTimeout(function() {                    
    _this.animation.translate(-_this.windowWidth - 300, item.y).step();
    item.animationIndex = _this.animation.export();
  }.bind(_this),1000);
})(item);

《javascript高级程序设计》中有说到:this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this等于window,而当函数被作为某个对象调用时,this等于那个对象。不过,匿名函数具有全局性,因此this对象同常指向window

不过针对于匿名函数this具有全局性的观点仍是有争议的,具体this作用域问题可参考
【Javascript】深入理解this作用域问题以及new运算符对this作用域的影响

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