Sean
Sean

Reputation: 789

How does new wrapper work in JavaScript?

In the context of underscore.js:

// Create a safe reference to the Underscore object for use below.
   var _ = function(obj) { return new wrapper(obj); };

Simply put, what does this function return?

Upvotes: 0

Views: 554

Answers (2)

Bergi
Bergi

Reputation: 664454

It is a wrapper function for the wrapper constructor to allow you using underscore without the new keyword. Calling underscore will always return a new wrapper instance.


Btw, the wrapper function has been removed in this commit. The _ function itself is the constructor now, see Understanding the declaration of the underscore in _.js? for explanation.

Upvotes: 1

SReject
SReject

Reputation: 3936

simply put, it's a constructor for 'wrapper' to make things a big easier for you

// this allows you to do things such as:
var a = _({/*object*/});

// rether than something like:
var a = new wrapper({/*object*/});

I think in the since of underscore.js it's to keep your coding tiddy and simple :)

Upvotes: 0

Related Questions