1

Say I have a simple Javascript object:

var Thing = function (data) {
    this.data = data;
}

Would there be a shorter way of doing something like the following?:

var makeThing = function(data) { return new Thing(data); };
var things = $.map(array, makeThing);
2
  • @RobG: I strongly suspect alias for jQuery; the OP is invoking jQuery.map. Commented Feb 27, 2014 at 2:31
  • Indeed, it is jQuery or Zepto's $ alias! Commented May 16, 2020 at 6:15

1 Answer 1

3

The shortest I can see is

var things = $.map(data, function(x) { return new Thing(x); })

as a trivial compression.

If you are sure you can do newer JS,

var things = data.map(function(x) { return new Thing(x); })

is shorter still.

Sign up to request clarification or add additional context in comments.

2 Comments

But is it possible to reference the constructor of the object as a function? Something like: data.map(Thing.constructor)
Thing is the constructor function. However, you won't get a new object from it without the new operator. JavaScript works a little bit like Objective C in this regard - when you do [[Thing alloc] init], with two different functions for allocation and initialisation of the object. new is allocating a new object; Thing is setting it up (and is termed "constructor"). You can invoke the "constructor" on anything, but it will just end up tacking extra properties on an existing object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.