Barry Tormey
Barry Tormey

Reputation: 3126

Underscore.js map not working with new objects

I am experiencing some very odd behavior with underscore.js _.map function.

It seems as though when I try to "new up" an object inside the function, it fails. But without a new object inside the function, it works as expected. Am I missing something here?

The following does not work (i.e. it prints nothing). It seems to be failing after the new object is created:

var test = { a: "test" };

var foo = _.map(data.A, function (dataItem) {
    var a = new test();

    console.log(a);
    return a;
});

But this does work:

var test = { a: "test" };

var foo = _.map(data.A, function (dataItem) {
    var a = dataItem;

    console.log(a);
    return a;
});

And the above logs all of the items in the data.A array.

Upvotes: 0

Views: 503

Answers (2)

SomeShinyObject
SomeShinyObject

Reputation: 7811

This isn't really an Underscore.js issue but more of a JavaScript object issue. Since test is an object literal, you'll need to use Object.create(). This will take test and make a new object

var a = Object.create(test);

Fiddle

Reference: Creating new objects using object literals

MDN Object.create***

*** If you don't have access to Object.create due to browser limitations, this MDN page has a polyfill function at the bottom.

Upvotes: 0

tavi
tavi

Reputation: 594

The reason your code doesn't work is caused by these lines:

var test = { a: "test" };

and

var a = new test;

You have to declare test as a function:

var test = function () {
   return  { a: "test" };
}

in order to use the new operator.

The issue is not related with underscore.js or with the map function but with javascript in general.

Upvotes: 1

Related Questions