0

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.

Barry Tormey
  • 2,966
  • 4
  • 35
  • 55

2 Answers2

1

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.

tavi
  • 594
  • 6
  • 15
0

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.

Community
  • 1
  • 1
SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59