Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created May 17, 2013 10:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save miguelmota/5598264 to your computer and use it in GitHub Desktop.
Call and Apply methods in JavaScript. Blog post: http://www.miguelmota.com/blog/call-and-apply-methods-in-javascript/
//
// Simple demonstration Call and Apply methods
//
// Square object with a color property and 2 methods
var square = {
color: "red",
getColor: function () {
return "I am the color " + this.color + "!";
},
getArea: function (width, height) {
return "My area is " + (width * height) + " feet!";
}
};
// Call getColor method
console.log(square.getColor()); // I am the color red!
// Call getArea method with 2 arguments
console.log(square.getArea(4, 4)); // My area is 16 feet!
// Rectangle object with color property only
var rectangle = {
color: "blue"
}
// Using call method on the getColor function of square object
console.log(square.getColor.call(rectangle)); // I am the color blue!
// Using call method without a context
console.log(square.getColor.call()); // I am the color undefined!
// Setting a color property on window object
window.color = "green";
// Using call method without a context again
console.log(square.getColor.call()); // I am the color green!
// Using call method on window object
console.log(square.getColor.call(window)); // I am the color green!
// Using call method on getArea function of square object and passing in 2 parameters
console.log(square.getArea.call(rectangle, 6, 4)); // My area is 24 feet!
// Defining an array with 2 values
var sides = [6, 4];
// Using apply method on getArea function of square object and passing in array as parameter
console.log(square.getArea.apply(rectangle, sides)); // My area is 24 feet!
// Define an array with numbers
var numbers = [22, 4, 354, 54, 546, 85, 12, 98];
// Using apply method to pass in array of numbers
console.log(Math.max.apply(Math, numbers)); // 546
//EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment