Javascript 当JSON对象返回(并且该对象超出范围)时,如何设置原型对象?

Javascript 当JSON对象返回(并且该对象超出范围)时,如何设置原型对象?,javascript,Javascript,我的目标如下: //the constructor function function NewsScroller() { } //now put some config objects using the JSON structure NewsScroller.prototype.config = { serviceUrl : '/NewsProvider.svc/rest/GetNews/', pageIndex : 0,

我的目标如下:

 //the constructor function
    function NewsScroller() {

    }


    //now put some config objects using the JSON structure
    NewsScroller.prototype.config = {
        serviceUrl : '/NewsProvider.svc/rest/GetNews/',
        pageIndex : 0,
        pageNumbers: 0
    }

//allows the sending of a page
NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex;


    $.getJSON(urlToGetJson, function (data) {


    alert(this.config.pageNumbers);


        $.each(data.NewsItems, function (i, item) {

            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);

        });

    });


}
这会引发错误:

this.config未定义[Break On] 此错误] 警报(this.config.pageNumbers)

我可以从代码中看出,我无法访问原型,因此我有两个问题:

1) 为什么我无法访问?为什么超出范围?函数中的函数肯定可以访问该函数中包含的成员?
2) 如果我无法访问它,我如何在“config”对象表示法中设置对象“pageNumbers”?

它超出了范围,因为执行函数的是jQuery的ajax回调,因此这会丢失上下文。实际上,其他变量保留其词法范围,因此您可以使用
self=this
模式解决此问题,或者尝试绑定函数:

NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex;
    function ajaxCallback(data) {
        alert(this.config.pageNumbers);
        $.each(data.NewsItems, function (i, item) {
            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);
        });
    }

    $.getJSON(urlToGetJson, $.proxy(ajaxCallback, this));

}
使用
self=this
模式:

NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex,
        self = this;

    $.getJSON(urlToGetJson, function(data) {
        alert(self.config.pageNumbers); // instead of this, we reference self
        $.each(data.NewsItems, function (i, item) {
            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);
        });
    });

}

这太棒了,我不知道self=这个设计模式!谢谢