Currently your object literal creates an object with two properties, currentActiveCategories
, which is an array, and currentValue
, which is set to the result of calling addValues()
at the time the object literal is evaluated. You are trying to call the function with this.currentActiveCategories
, which will be undefined
, because this
is not equal to that object at that moment.
If the idea is to have a function that can return the current total at any time you can do this:
var primaryCare = {
currentActiveCategories : [ "1", "2"],
currentValue : function () {
var tempTotal = "";
for(var i = 0; i < this.currentActiveCategories.length; i++){
tempTotal += this.currentActiveCategories[i];
}
return tempTotal;
}
}
primaryCare.currentValue(); // returns "12", i.e., "1" + "2"
Always declare your variables with var
or they'll become globals - note that you can't declare an int
in JS. You need to initialise tempTotal
to an empty string before you start adding strings to it, or instead of "12"
you'll get "undefined12"
.
When you call a function as a method of an object, like primaryCare.currentValue()
(as shown above) then within the function this
will be set to that object.
It seems kind of odd to me to be adding the values as strings. If you want to use numbers and get a numeric total you can do this:
var primaryCare = {
currentActiveCategories : [ 1, 2], // note no quotes around the numbers
currentValue : function () {
var tempTotal = 0;
for(var i = 0; i < this.currentActiveCategories.length; i++){
tempTotal += this.currentActiveCategories[i];
}
return tempTotal;
}
}