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, transa开发者_如何学Goctions) {
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!
Change
next += $.isPlainObject(val) ? printObj(val) : val;
to:
next += $.isPlainObject(val) ? breakdown.printObj(val) : val;
You should probably have breakdown.printObj(val)
rather than just printObj(val)
in line 6.
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.
精彩评论