0

Hi I am getting an uncaught reference exception on my code.This is what I have:

 var config = {
    debug: true,
    data: {
        debug: false,
        logErrorsOnServer: true,
        defaultCulture: '',
        serviceUrl: ''
    },

    init: function(options) {
        if (!options) {
            return;
        }          
        if (options.hasOwnProperty('debug')) {
            data.debug = options.debug;
        }

    },
};

When I try to get the value of data.debug I get an uncaught reference error that says:

UncoughtReference Error: data is not defined

Whay can't I acces my data object?

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
aleczandru
  • 5,319
  • 15
  • 62
  • 112
  • 1
    Could be wrong here but try this.data.debug – Dominic Green Jun 19 '13 at 10:59
  • What is going wrong. At a first glance everything okay in Chrome devtools – Thomas Junk Jun 19 '13 at 11:00
  • data.debug = options.debug throws UncoughtReference Error: data is not defined – aleczandru Jun 19 '13 at 11:00
  • I don't get it. You have config.debug, data.debug and options.hasOwnProperty('debug'). In my view, that's two to many. – Lennart Jun 19 '13 at 11:03
  • Well, you have no variable `data` as far as I can see. If you want to to access the `data` property of the `config` object, you have to use `config.data` or `this.data`, assuming you call the function with `config.init()`. JavaScript doesn't have any hidden magic like Java where `this.` is implicit (and that's a good thing). It does exactly what you tell it to do (most of the time). – Felix Kling Jun 19 '13 at 11:05

2 Answers2

1

You need to say:

this.data.debug = options.debug;

...assuming that you are calling the init() function in a way that sets this to the (outer) object, e.g., with config.init().

Or you can say:

config.data.debug = options.debug;

The reason you got an error about data not being defined when you tried to use data.debug directly is that in fact data is not defined as a variable, it is a property of the object. Just because init() is a method on your object doesn't mean it automatically references other object properties.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

Well, the data variable is undefined. You probably want to use the object on your .data property of config (accessible via the this keyword):

…
    if (options.hasOwnProperty('debug')) {
        this.data.debug = options.debug;
    }
…

See also Javascript: Object Literal reference in own key's function instead of 'this' for different methods to access .data.

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