Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Created November 4, 2015 17:31
Show Gist options
  • Save joshuakfarrar/f4e70d44da41b8e3df38 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/f4e70d44da41b8e3df38 to your computer and use it in GitHub Desktop.
# binding values to 'this' via `fn.call()` and `fn.apply()`
> var person = { name: 'sent1nel' }
> (function print(){ console.log(this.name); }).call(person);
sent1nel
> (function print(){ console.log(this.name); }).apply(person);
sent1nel
# passing in args in addition to the bound scope
# the difference between `fn.call()` and `fn.apply()` is that
# apply accepts an array of arguments instead of a list
> var people = [ person, { name: 'vippy' }];
> for (var i = 0, len = people.length; i < len; i++) {
... (function print(i) {
..... console.log("#" + i + " " + this.name);
..... }).call(people[i], i);
... }
#0 sent1nel
#1 vippy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment