I am working on underscore.js and I got stuck in the very first function.
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Test Examples
var obj = {
name : 'Francis',
gender: 'male'
}
var test = _(obj);
console.log(test); // _ {_wrapped: Object}
// Why statement this._wrapped = obj; still got executed?
var Man = function() {
this.age = 30;
this.people = "John";
return this;
this.man = "me";
}
var me = new Man();
console.log(me) // Man {age: 30, people: "John"}
// There is no "man" property because function Man returns
// before executing to the last statement.
I am trying to figure out what _
(underscore) does in here: I think it serves as a constructor and returns an instance with all the functions defined in underscore.js. So it'll be more convenient to invoke the functions with simple syntax.
Fox example:
var anotherList = [1, 2];
_.each(anotherList, alert); // alert "1", "2"
var anotherObj = {"name": "H"};
var anotherObj = _(anotherObj);
anotherObj.each(alert); // alert "H"
But what's the mechanism behind all this?
How this._wrapped = obj;
works?
The
_
function is recursive. You call it, then it calls itself a second time. Let's take a look.When you do
_(obj)
withobj={...}
, your object fulfills the secondif
condition --this
is not an instance of_
, as it was not called as a constructor (this
is the global object). Then, it returnsnew _(obj)
, calling_
as a constructor. This second time around,this
is indeed an instance of_
, so neither condition is fulfilled. Now, it reaches the final line. Being a constructor, it implicitly returnsthis
to the first time you called it.You now have a
_
object.