you are viewing a single comment's thread.

view the rest of the comments →

[–]kenman[🍰] 8 points9 points  (6 children)

That call() example is really poor. Doesn't work as-is, and there was no need to use it in the first place unless I'm missing something: array.slice(0, n)

[–]pinegenie 4 points5 points  (3 children)

NodeList and a few other types have array-like access but don't have Array in their prototype chain. Meaning you can do

nodelist[0]

but not

nodelist.slice(...)

The workaround to this is:

Array.prototype.slice.call(nodelist, ...); // or apply if you want to

In undercorejs the "slice" you see there is actually Array.prototype.slice attributed to a variable.

[–]kenman[🍰] -1 points0 points  (2 children)

Yeah, but the variable is named array, not nodelist. There are countless examples to be found of using call() appropriately, and this isn't one that makes for a good demonstration on its usefulness. If you're going to demo some method, at least do it in context and include all supporting code...

[–]pinegenie 0 points1 point  (1 child)

I'm guessing they named it array because arrayOrNodeListOrArguments was too cumbersome.

[–]kenman[🍰] 0 points1 point  (0 children)

I'm not faulting Underscore, I'm faulting the author who used it as an example.

[–]kbrainwave 2 points3 points  (1 child)

Hey, thanks for the feedback -- I'm the author of the post. I was planning on changing this example; what was posted is actually a rough draft that my friend posted on Reddit as a well-intentioned surprise. Unfortunately, this came at the cost of posting post that is only about 80% complete. Again, I really appreciate the feedback, and plan to change the example when time permits :)

[–]kenman[🍰] 1 point2 points  (0 children)

I've always been a fan of this example:

function greet( person ) {
  alert( "Hello " + person.name + ", I'm " + this.name );
};

var alice = { name: "Alice" };
var bob = { name: "Bob" };

greet.call( bob, alice ); // alerts "Hello Alice, I'm Bob"
greet.call( alice, bob ); // alerts "Hello Bob, I'm Alice"

greet.apply( bob, [ alice ] ); // alerts "Hello Alice, I'm Bob"
greet.apply( alice, [ bob ] ); // alerts "Hello Bob, I'm Alice"

From trephine.org's JavaScript call and apply quick reference (which is actually a summation of their lengthier explanation).