Skip to content

Instantly share code, notes, and snippets.

@jamc92
Created February 22, 2015 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamc92/a3e7ec739088869adfdd to your computer and use it in GitHub Desktop.
Save jamc92/a3e7ec739088869adfdd to your computer and use it in GitHub Desktop.
JS - Call()
//Playing with call() method from JS
function sayFavoriteFood() {
console.log(this.sayFavoriteFood);
}
// create a desmond object
var javier = {
favoriteFood: 'kiwi';
};
// create a maya object
var juan = {
favoriteFood: 'pina';
};
//invoking from the globval scope where favoriteFood doesn't exist
sayFavoriteFood(); //logs undefined
//invoking as if within the desmond object
sayFavoriteFood.call(desmond); //logs "apple"
//invoking as if within the maya object
sayFavoriteFood.call(maya); //logs "orange"
function sayThings(something, somethingElse) {
console.log(something + ' and ' + somethingElse);
}
//logs "meow and woof" x 2
sayThings("Meow", "Woof");
sayThings(this, "Mewo", "Woof");
function logArguments(a, b, c) {
console.log(arguments);
}
logArguments(1, 4, 9); //logs [1, 4, 9]
//using 'argument' with call() method
function logJoinedArguments(a, b, c) {
var joined = Array.prototype.join.call(arguments, '-');
console.log(joined);
}
logJoinedArguments(1, 4, 9); //logs "1-4-9"
function reverseArguments(a, b, c){
console.log('a = ' + a);
Array.prototype.reverse.call(arguments);
console.log('a = ' + a);
}
reverseArguments(1, 4, 9) //logs "a = 1" then "a = 9"
// copying arguments with .slice
var argsCopy = Array.prototype.slice.call(arguments);
// or less efficient
var argsCopy = [].slice.call(arguments);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment