Skip to content

Instantly share code, notes, and snippets.

@mannuelf
Created June 15, 2014 17:41
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 mannuelf/0843adf99c092f44ba94 to your computer and use it in GitHub Desktop.
Save mannuelf/0843adf99c092f44ba94 to your computer and use it in GitHub Desktop.
Invoking a Function
// functions are invoked using four different scenarios or patterns
/*
1. As a function
2. As a method
3. As a constructor
*/
// function pattern
var myFunction = function(){
return 'foo';
};
console.log(myFunction());
// method pattern
var myObject = { myFunction: function(){ return 'bar' }}
console.log(myObject.myFunction());
// constructor pattern
var Manny = function(){
this.living = true,
this.age = 32,
this.gender = 'male',
this.getGender = function() { return this.gender; };
};
var manny = new Manny(); // invoke via Manny constructor
console.log(manny);
// apply() and call() pattern
var greet = {
runGreet: function() {
console.log(this.name, arguments[0],arguments[1]);
}
};
var manny = { name:'manny'};
var refilwe = { name:'refilwe'};
// invoke the runGreet function as if it were inside of the cody object
greet.runGreet.call(manny, 'foo', 'bar');
// invoke the runGreet function as if it were inside of the refilwe object
greet.runGreet.apply(refilwe, ['foo', 'bar']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment