Having some trouble getting ‘this’ to behave as I would expect it –
Basically, I have an object, and I am unable to access an array in the object from a function within the same object –
It looks like this:
var articles = {
article : {
1: {
title : 'This is a Title',
content : 'This is the content of the article'
},
2: {
title : 'This is the second article',
content : 'This is the second article content'
},
3: {
title : 'This is the third article',
content : 'Making information transferrable. Identifiable. Manipulatable.'
}
},
numArticles : function(){
var size = 0, key;
for (key in this.article){
if(this.article.hasOwnProperty(key)) size++;
}
return size;
},
buildInterface : function(){
var aSize = this.numArticles();
for(var i = 0; i < aSize; i++){
$('body').append('<article><h2>' + this.article[i].title + '</h2></article>');
}
}
}
the buildInterface() function is not able to access the ‘article’ array in this scenario.
Here is an example of this in progress:
http://jsfiddle.net/merk/xV2n6/41/
Any help here would be appreciated –
I have a hunch it may be a scoping issue – hopefully it is not something related to JSFiddle –
Thanks a ton –
Peace
Mark
You have inconsistent indexing for your
articlevariable: properties are defined beginning from1, yet you start from0inbuildArticlesmethodforloop. You can fix this with…… or (and that’s much better for my taste, as you’re basically trying to use Object for the Array’s work) rewrite the
articledefinition into a proper Array:… leaving your buildArticles
forloop as it is now (as indexing now properly starts from 0).BTW, this way you don’t even have to make a special function to count your articles:
article.lengthwould be quite enough.Here’s JS Fiddle with this approach’s illustration.
As a sidenote, if you had actually checked the debugger, you would have noticed that it’s
this.articles[0]that isundefined(so trying to taketitleout of it is wrong), and notthis.articles. Hence it’s definitely not a question of scope.