I have the following object:
//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);
});
});
}
Which throws the error:
this.config is undefined [Break On
This Error]
alert(this.config.pageNumbers);
I can see from looking at the code I cannot access the prototype so I have 2 questions:
1) Why cant I access why is it out of scope? Surely a function in a function has access to the memebers contained within that function?
2) If I cant access it how do I set the object ‘pageNumbers’ in the ‘config’ object notation?
It’s out of scope because
thisloses context, since it’s jQuery’s ajax callback that is executing the function. Indeed other variables retain their lexical scope, so you can solve this with theself=thispattern, or try binding the function:Using the
self=thispattern: