Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to understand underscore.js source - call and apply used in library
    primarykey
    data
    text
    <p>In Jeremy Ashkenas's awesome Underscore.js library, I tried to understand one thing about the source file. I do not understand this:</p> <pre><code>var slice = Array.prototype.slice; args = slice.call(arguments, 2); </code></pre> <p>So that:</p> <pre><code>args = Array.prototype.slice.call(arguments, 2); </code></pre> <p><code>.call</code> or <code>.apply</code> are the methods of the functions. But here, which functions do <code>.call</code> refer to? The first parameter should be the context, but <code>arguments</code> is context? The second parameter should be the params to pass in the functions. Here they are number <code>2</code>. What does this mean? Sometimes in the library, it uses <code>1</code> or <code>0</code>. Are they the number of the params to pass in the functions?</p> <pre><code>_.bind = function bind(func, context) { var bound, args; if (func.bind === nativeBind &amp;&amp; nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; </code></pre> <p>Question 2: I do not quite understand the logic of this function. Need help to understand. An example should be very helpful.</p> <pre><code> // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); return _.map(obj, function(value) { return (method.call ? method || value : value[method]).apply(value, args); }); }; </code></pre> <p>Thank you for help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload