Skip to content

Instantly share code, notes, and snippets.

@AugustoPedraza
Created March 4, 2013 15:01
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 AugustoPedraza/5082802 to your computer and use it in GitHub Desktop.
Save AugustoPedraza/5082802 to your computer and use it in GitHub Desktop.
Because JavaScript is a functional object-oriented language, functions can have methods. The "apply" methods lets us construct an array of arguments to use to invoke a function. It also lets us choose the value of "this". The "apply" methods takes two parameters. The first is the value that should be bound to "this". The second is an array of pa…
add = function(a, b){ return a + b; };
//Make an array of 2 numbers and add them.
var array = [3, 4];
var sum = add.apply(null, array); //sum is 7
console.log(sum);
/*----------------------------------------*/
var Quo = function(string){ this.status = string; };
Quo.prototype.getStatus = function( ){ return this.status; };
//Make an object with a status member.
var statusObject = {
status: 'A-OK'
};
//statusObject does not inherit from Quo.prototype,
//but we can invoke the get_status method on statusObject
//even though statusObject does not have a getStatus method.
var status = Quo.prototype.getStatus.apply(statusObject);
console.log(status); //Show 'A-OK'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment