setInterval,这个,又 [英] setInterval, this, again

查看:40
本文介绍了setInterval,这个,又的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 setInterval 的问题,我无法弄清楚.

I have a problem in regard to setInterval that I can't figure out.

从对象内部调用 setInterval 或 timeout 时范围存在问题,但我仍然无法理解它.

There is the problem with the scope when calling setInterval or timeout from within an object, but still I can't wrap my head around it.

我试图把我的东西放在一个匿名函数中,它不起作用.

I tried to put my stuff inside an anonymous function, it won't work.

这基本上是我的问题,简化为基本问题:

This is basicly my problem, simplified to the bare bones:

function Scenario(){
    var ships = [];
    this.ini = function(){
        for (var i = 0; i < ships.length; i++){
            timeoutID1 = setTimeout(ships[i].ding, 1000);
            timeoutID2 = setTimeout(ships[i].bing, 1000);
        }
    }
    this.setShips = function(){
        var ship = new Ship("ship");
        ships.push(ship);    
    }        

    function Ship(name){
        this.name = name;
        this.ding = function(){
            intervalID1 = setInterval(function(){
                console.log("ding");
            }, 500)      
        }
        this.bing = function(){
            var _this = this;
            intervalID2 = setInterval(function(){
                console.log(_this.name);
            }, 500)      
        }
    }
    this.setShips();
}

var scenario = new Scenario();
scenario.ini();

http://jsfiddle.net/ancientsion/xkwsn7xd/

基本上,console.log("ding") 有效,console.log(_this.name) 无效.

Basicly, console.log("ding") works, console.log(_this.name) doesn't.

为什么?

推荐答案

setTimeout() 开始调用你的方法时,它只会看到函数而不是调用上下文(即将其绑定到的对象);很像这样:

By the time setTimeout() gets around to call your method, it only sees the function and not the invocation context (i.e. the object to bind it to); much like this:

var bing = ships[i].bing;

bing(); // inside bing(), this == window

基本上,您需要为 setTimeout() 提供一个预先连接的方法调用:

Basically, you need to provide setTimeout() with a prewired method invocation:

var bound_bing = ships[i].bing.bind(ships[i]);
timeoutID2 = setTimeout(bound_bing, 1000);

魔法"发生在 .bind() 因为它返回一个新函数,该函数将正确设置 this.

这篇关于setInterval,这个,又的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆