0

Consider the following example:

var $_dfd = $.Deferred(),
    $_x = {};

$_x = {
    a: 1,
    b: 2
};

console.log($_x); // Gives {a: 1, b: 2, more: {c: 3, d: 4}} <== Weirdness here
console.log($_x.a); // Gives 1
console.log($_x.more); // Gives undefined

$_dfd.pipe(function($_x) {
    $_x.more = {
        c: 3,
        d: 4                    
    };

    return $_x;
});

$_dfd.resolve($_x).done(function($_x) {
    console.log($_x); // Gives {a: 1, b: 2, more: {c: 3, d: 4}}
});

​ I am really totally baffled by console.log output #1. There are two questions that need to be answered:

  1. What's the real state of the variable $_x at the first console.log output?

  2. If console.log is not a safe way to understand the state of variables when working with deferred, what are other better alternatives?

Thanks!

gsklee
  • 4,774
  • 4
  • 39
  • 55
  • Not sure about the deferred issue, but note that there's no point initialising `$_x` to an empty object when you immediately throw that away and assign it equal to a second object. – nnnnnn Aug 13 '12 at 10:56
  • P.S. I remembered I'd seen something before about `console.log()` behaving like this: http://stackoverflow.com/q/11118758/615754 - one workaround is to clone the object before you log it: `console.log(JSON.parse(JSON.stringify($_x)));` – nnnnnn Aug 13 '12 at 11:03
  • @nnnnnn is right, if you debug and step over it - it produces the correct output. Using the clone trick works as well http://jsfiddle.net/2tfTr/ – Ian Bishop Aug 13 '12 at 16:58
  • Found the answer here: http://stackoverflow.com/questions/8249136/why-does-javascript-object-show-different-values-in-console-in-chrome-firefox – gsklee Aug 14 '12 at 01:58

1 Answers1

0

Have to use JSON.stringify(), as detailed in the following post:

Bug in console.log?

Community
  • 1
  • 1
gsklee
  • 4,774
  • 4
  • 39
  • 55