views:

466

answers:

3

I have a JavaScript object that looks like the following:

venue = function(map, dataSet) {
    // set some constants
    this.VENUE_ID = 0;
    this.VENUE_NAME = 1;
    this.VENUE_CITY = 2;

    this.filterBy = function(field, value) {
        ...
        var filterValue = 'parent.VENUE_' + field;
    }
}

Now, the problem is that I need the value of filterValue to contain the value of the constant on the parent object. Currently I have tried using the method shown above and then referencing the filterValue when trying to access the array item, but this simply returns undefined.

How do I convert the filterValue variable into the value of the constant it represents?

+3  A: 

This has nothing to do with the variable scope.

var filterValue = this['VENUE_' + field];

would do.

BYK
+1  A: 

Try this:

var filterValue = this['VENUE_' + field];
Gumbo
+2  A: 

JavaScript has no concept of 'parent'. And I think you're confusing scope and context. If that method was written as var filterBy() you'd have to access it in a different 'scope'. But by using 'this' you kept in in the same object as it was written. So everything you wrote is in 'this' context.

mwilcox
Ah I see! Well thank you, I had no idea. I had been manually setting the parent to 'this' externally to each function up until this point. I think the reason was something to do with using functions as callbacks.
tombazza