1

I'm just picking up Javascript, and I don't understand this problem.

I have created a custom object called DeleteReasonCodes with an instance variable called delReasonCodes, declared as an array. However, the inner methods can't seem to see this instance variable. Every time I try to run it, I get a delReasonCodes is not defined error.

Perhaps I'm just not understanding the Javascript scoping rules?

var DeleteReasonCodes = {

    delReasonCodes: [],

    get: function ()
    {
        return delReasonCodes;
    },

    add: function (code, desc)
    {
        delReasonCodes.push(new DeleteReasonCode(code, desc));
    }
};
Mario S
  • 11,715
  • 24
  • 39
  • 47
asteri
  • 11,402
  • 13
  • 60
  • 84

3 Answers3

2

No, javascript scoping belongs to functions (and nothing else).

The only variable you have created is DeleteReasonCodes, and you have assigned it an object with 3 properties. You can access them via a property accessor operator if you have a reference to the object. In your case, you could use this.delReasonCode or DeleteReasonCodes.delReasonCode - see this answer for the difference.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You're treating a JavaScript object as you would a class in another language. Local-scope in JavaScript only resides inside functions, not objects. In your case, you need to access the data with a fully-qualified name:

DeleteReasonCodes.delReasonCodes.push();
Matt
  • 41,216
  • 30
  • 109
  • 147
0

If you do this

delReasonCodes: [],

get: function() {
    return this.delReasonCodes;
},
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77