turbonerd
turbonerd

Reputation: 1306

ReferenceError from a JavaScript function that is defined correctly?

I've declared myself a JavaScript object called "breakdown".

I've then borrowed a function which I found on the jQuery extend() documentation, which works perfectly well on a different page, but identical setup - rewards object instead of breakdown.

breakdown = {};

breakdown.printObj = function(obj) { 
    var arr = []; 
    $.each(obj, function(key, val) { 
        var next = key + ": "; 
        next += $.isPlainObject(val) ? printObj(val) : val; 
        arr.push( next ); 
    }); 
    return "{ " +  arr.join(", ") + " }"; 
} 

I'm then trying to use it as I have on the other page to see what is in my "categories" array:

breakdown.getPointsBreakdown = function(categories, transactions) {

    alert( breakdown.printObj(categories) );

If I "typeof" that alert instead, it displays "object". If I alert "categories[1].Title", it displays "Good Behaviour", so the array is being passed to the categories variable in this function correctly.

However, when I use "breakdown.printObj", I get the following error in FireBug:

ReferenceError { message="printObj is not defined", fileName="https://frog.ashingtonh...7fa8452ccb3e94ba89e487a", more...}

I don't understand how!

Upvotes: 1

Views: 250

Answers (3)

Matt Ball
Matt Ball

Reputation: 360056

Change

breakdown.printObj = function(obj) { 
    // snip...
};

to

breakdown.printObj = function printObj(obj) { 
    // snip...
};

so that you can call it recursively.

This is called named function expression.

Upvotes: 1

Exelian
Exelian

Reputation: 5888

Change

    next += $.isPlainObject(val) ? printObj(val) : val; 

to:

    next += $.isPlainObject(val) ? breakdown.printObj(val) : val; 

Upvotes: 1

JacquesB
JacquesB

Reputation: 42689

You should probably have breakdown.printObj(val) rather than just printObj(val) in line 6.

Upvotes: 1

Related Questions