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?