Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore js extend method

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?

like image 628
sat Avatar asked Sep 18 '12 03:09

sat


People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What does underscore mean in JavaScript?

In JavaScript, the dollar sign ($) and underscore (_) are both identifiers—similar to any other name, like myCar or houseAge. You can use a dollar sign or underscore to identify objects, such as: Variables. Functions.

How do you extend an object in JavaScript?

The extends keyword can be used to extend the objects as well as classes in JavaScript. It is usually used to create a class which is child of another class. Syntax: class childclass extends parentclass {...}


1 Answers

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.

like image 96
mu is too short Avatar answered Oct 04 '22 08:10

mu is too short