javascript类和上下文的问题

时间:2010-02-01 13:56:17

标签: javascript

在下面的代码中,我想通过第三方API中的函数调用回调来调用方法 OpenNextPage 。这个方法第一次被一个名为Corridor的类的实例调用。在第一次调用之后,通过传递给 LoadPage 方法的callBack再次调用该方法,直到Api函数getCorridors不再返回任何走廊。

我发现了一些与执行环境有关的问题。 OpenNextPage方法应始终在第一次执行的相同上下文中执行(其中mC是保存此实例的对象)。但是这没有发生,OpenNextPage是在不同的上下文中调用的。有什么想法吗?

干杯

function startExec()
{
    var mC = new Corridor();
    mC.OpenNextPage();
}

Corridor.prototype.OpenNextPage = function()
{
    if(this.KeepLoading == false)
    {
        if(this.KeepLoadingTimer)
            clearTimeout(this.KeepLoadingTimer);        

        return 0;
    }

    this.ShowLoadingCorridorMsg();        
    this.LoadPage(++this.LoadedPages, this.OpenNextPage, 3 * this.ItemsPerPage);
}

//********************************************************************************
//Private
Corridor.prototype.LoadPage = function(page, callBack, pageSize)
{
    var ref = this;

    var mt = new MWsTraffic();
    var city = new MCity();

    city.name = cityList.getCurrentCity().name;
    city.state = cityList.getCurrentCity().state;

    var rr = new MResultRange();

    //This function is defined in a sort of public API available on the partner web site. 
    //So, as far as I know, the execution context will be changed and as of this point the 'this' will refer
    //to another object, that's why I have a this reference in the ref variable. This is what I think
    mt.getCorridors(city, rr,
        function(cInfo)
        {
            if (cInfo == null) 
            {   
                ref.KeepLoading = false;
                return null;
            }

            if( (cInfo.recordCount == 0) ) 
            {
                ref.KeepLoading = false;
                return null;
            }

            var e;
            for (var i = 0; i < cInfo.recordCount; i++) 
            {
                e = cInfo.corridor[i];                
                ref.totalCorridorsArray.push( new corridorContents(e.codCorridor, e.nameCorridor, e.levelCongested, e.point.x, e.point.y, false) );
            }

            if(callBack != null)
            {
                //Corridor.call(ref, callBack);
                callBack(); // <----  here's is the problem. This callback which points to the OpenNextPage function is being executed in another context. 
                            // I want to execute it in the same context OpenNextPage was called originaly (from inside startExec mC object)
            }
        }
    );    
}

1 个答案:

答案 0 :(得分:1)

你应该使用某种“绑定”设施。这将有助于你

function bind(context,fncname){
    return function(){
        context[fncname].apply(context,arguments);    
    }
}

var openNextPage = bind(this,"OpenNextPage");
this.LoadPage(++this.LoadedPages, openNextPage, 3 * this.ItemsPerPage);

或者代替callBack做

callBack.call(ref);

但是“bind”更好,因为有时你想要将回调传递给一些没有指向“this”的外部函数。因此,通过绑定它们,您将始终拥有正确的范围。