Created
February 22, 2015 16:16
-
-
Save jamc92/a3e7ec739088869adfdd to your computer and use it in GitHub Desktop.
JS - Call()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sayThings(something, somethingElse) { | |
console.log(something + ' and ' + somethingElse); | |
} | |
//logs "meow and woof" x 2 | |
sayThings("Meow", "Woof"); | |
sayThings(this, "Mewo", "Woof"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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