11

Looks like Underscore library won't treat functions in JSON as first class citizens. Why doesn't this fiddle work?

http://jsfiddle.net/anV28/

var a = { 'f1': function(){var s='success';} };
var b = {'foo' : 'bar'};
var c = _.extend(b, a);
alert(JSON.stringify(c));

var d = _.extend({name : 'moe'}, {age : 50});
alert(JSON.stringify(d));

Why isn't c the right value?

d seems to have the right value if we only use strings as keys and values.

How can I get around this limitation?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
sat
  • 5,489
  • 10
  • 63
  • 81
  • This question let me remember the [answer](http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object) from John Resig again. – haudoing May 08 '13 at 16:21

1 Answers1

12

c does have the right value:

{
    f1: function () {var s='success';},
    foo: "bar"
}

Your problem is that you're using JSON.stringify to produce strings for alert, there is no representation of a function in JSON so JSON.stringify(c) leaves f1 out. If you use console.log to view your results you'll have better luck: http://jsfiddle.net/ambiguous/7j7hu/

As an aside, you should keep in mind that using _.extend this way:

var c = _.extend(b, a);

will also modify b and that might not be your intent.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    Perfect. Thank you! I would have never known the problem was with JSON.stringify – sat Sep 18 '12 at 04:21