Apologies if this isn’t a well constructed post – I’m writing it on my phone because I’m in a meeting but can’t get this out of my head!
I’ve created an object, as follows:
/* CLASS = "HPAnalysisObject" */
/* CONSTRUCTOR */
var HPAnalysisObject = {
points_total: new Array(),
getHPTotals: function(house_id, label) {
for (var i = 1; i <= 26; i++) {
initial = String.fromCharCode(64 + i);
Frog.API.get("users.search", {
"params": {"surname": initial, "group": house_id},
"onSuccess": this.addUsers
});
}
alert(this.getArray());
},
getArray: function() {
return this.points_total;
},
setArray: function(array) {
alert(typeof(array));
},
addUsers: function(data) {
array = new Array(this.getArray);
for (var i = 0; i < data.length; i++) {
if (data[i].profile.id == 200) {
array.push(data[i].id);
}
}
this.setArray(array);
}
};
widget.onLoad = function(){
HPAnalysisObject.getHPTotals(10705, "eagles");
}
The getArray function throws:
TypeError: not a function.
How do you, pseudo, initialise an empty array on init; put new items into that array with one function; then return the array with another?
EDIT: I HAVE OVERHAULED MY PSEUDO-CODE WITH THE ACTUAL CODE
The problem is, once the
addUsersfunction is assigned to this property, you’re losing the originalthisscope. One quick solution (that doesn’t require a lot of restructuring) is to use a Function.prototype.bind polyfill:But, the more proper fix is to restructure your code to use a closure. With a closure, you can define functions that are “private” and bound to your object instance. Something in the lines of: