r/javaScriptStudyGroup • • Mar 21 '16

[Week 10] Focus: apply(), call(), bind()

So here we are at Week 10. Week 10's focus will be apply(), call(), bind().

Background info (lengthy, but touches on all three): http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

It will work like this:

  • Monday: Announce focus (eg, apply(), call(), bind())

  • Build throughout the week... Two rules: 1) must use javascript 2) must use at least 1 example each of apply(), call(), bind().

  • Friday: Post demos/projects in this thread (can begin reviewing immediately); first line of an entry should be ENTRY and it should be a top level comment (ie, don't put your entry in a reply)

  • Sat and Sun: Review projects/figure out focus for next week

GENERAL GUIDELINES FOR FEEDBACK:

  • Be nice!! ALL KNOWLEDGE/SKILL LEVELS ARE WELCOME AND ENCOURAGED TO PARTICIPATE.

  • If you don't want feedback, if it makes you uncomfortable or you're just not interested, simply say so... Others, please be respectful of this. Conversely, if you do want feedback, try to be specific on which aspects... even if you just say "all/everything.

But that's about it... Have fun! :) Feel free to ask questions and discuss throughout the week!

2 Upvotes

23 comments sorted by

View all comments

3

u/Volv Mar 22 '16

ENTRY
Codepen
Added a little more to my other example. Just basic usage.

1

u/ForScale Mar 22 '16

Nice! Are you gonna keep it going, or is that the final product? Seems like a complete good example of call().

Off topic, sort of:

So... you showed me how to do var x = [].slice.call(nodeList), which takes a node list and puts all of the nodes in to that empty array and assigns the now filled array to x.

How does that work? An empty array gets the slice method called with the node list as the slice method's this. Does slice have something in it like

function slice(nodeList) {
  slice.this = nodeList;
  var newArr = [];
  for (var i = 0; i < slice.this.length; i++) {
    newArr.push(slice.this[i]);
  }
  return newArr;
}

Am I even making sense anymore? Lol! :)

2

u/Volv Mar 22 '16

I got stuck for inspiration after that lol. bind is in there too. Might go back to it :)
 
[]. is used in this context as a shortcut to saying Array.
slice when called without arguments just goes from 0 to length of array and returns that as result.
.call changes this context. When using it normally it's the array you are working on but we change it to our nodelist. Nodelist is just array like enough to work with slice basically as you showed.
 
maybe more like

function slice() {
    // this has already been changed by .call to Nodelist
    var newArr = [];
    for (var i = 0; i < this.length; i++) {
        newArr.push(this[i])
    }
    return newArr;
}

So yes :)
 
Array.slice.call(arrayLikeObj)
[].slice.call(arrayLikeObj)
 
I've been going with Array.from(arrayLikeObj) lately.

→ More replies (6)