JavaScript_Succinctly
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Invoking a function (function, method, constructor, or call() and<br />
apply())<br />
Functions are invoked using four different scenarios or patterns.<br />
As a function<br />
As a method<br />
As a constructor<br />
Using apply() or call()<br />
In the following sample, we examine each of these invocation patterns.<br />
Sample: sample90.html<br />
<br />
// Function pattern.<br />
var myFunction = function () { return 'foo' };<br />
console.log(myFunction()); // Logs 'foo'.<br />
// Method pattern.<br />
var myObject = { myFunction: function () { return 'bar'; } }<br />
console.log(myObject.myFunction()); // Logs 'bar'.<br />
// Constructor pattern.<br />
var Cody = function () {<br />
this.living = true;<br />
this.age = 33;<br />
this.gender = 'male';<br />
this.getGender = function () { return this.gender; };<br />
}<br />
var cody = new Cody(); // Invoke via the Cody constructor.<br />
console.log(cody); // Logs the cody object and properties.<br />
// apply() and call() pattern.<br />
var greet = {<br />
runGreet: function () {<br />
console.log(this.name, arguments[0], arguments[1]);<br />
}<br />
}<br />
var cody = { name: 'cody' };<br />
var lisa = { name: 'lisa' };<br />
// Invoke the runGreet function as if it were inside of the cody object.<br />
greet.runGreet.call(cody, 'foo', 'bar'); // Logs 'cody foo bar'.<br />
98