Underlining the chain of internal processing

I'm curious how the _.chaining function is implemented and how (or better, why) it works the way it does.

Especially my question: where does the wrapper for each function take place. Suppose I use. _.chain(someArray).filter(...);When I enter a function, I see that the filter function has transformed into something like

function () { 
     var args = [this._wrapped]; //the data from chain(...)
     push.apply(args, arguments); //push to the (?) array
     return result.call(this, func.apply(_, args)); //?? where are these coming from?
}

I see that a function has 3 Closures in the scope (compare this with an un-chain function that shows the definition of a function without any original Closure function)

scope after using the chain function

The first is to find the function itself, the second is a "safe reference to the object itself," and the third to the underscore class itself.

When you call _.chain()how and where (by code), a conversion is performed (creating areas, etc.). I see that

//http://underscorejs.org/docs/underscore.html#section-139
 _.chain = function(obj) {
    return _(obj).chain();
  };

called and this applies to

//http://underscorejs.org/docs/underscore.html#section-145
//...
 chain: function() {
      this._chain = true;
      return this;
    },
//...

Then I'm stuck. I canโ€™t understand what comes from there. I assume that the magic happens inside the constructor, but I cannot figure out where the additional creation of Closures takes place. the functions themselves do not show any signs of wrapping, the chain call does not look like it is wrapping something. resultit seems, but I donโ€™t know where it is from. So where and how does this happen?

+4
source share
1 answer

_.chain(obj) _ _chain = true, _ _wrapped, ( ). _.mixin(_) #1210 (). _.mixin _ ( ! _.prototype). _.mixin _ ( , ).

:

function () {
  var args = [this._wrapped];
  push.apply(args, arguments);
  return result.call(this, func.apply(_, args));
}

(, , , func )

result :

var result = function(obj) {
  return this._chain ? _(obj).chain() : obj;
};

, , func.apply(_, args), _chain (_.chain ), _(obj).chain(), :)

, !

:

var _ = function(obj) {
  if (obj instanceof _) return obj;
  if (!(this instanceof _)) return new _(obj); // This line do the magic
  this._wrapped = obj;
};

:

func = function(a){this.a = a;}
b = func(2);
b.a // TypeError: Cannot read property 'a' of undefined
c = new func(2);
c.a // returns 2, whooa this the magical javascript!

( ),

- ?

0

All Articles