A JavaScript function is a block of code that may be executed when "someone" invokes (calls) it.
Example:
1 2 3 function myFunction(p1, p2) { return p1 * p2; // return the product of p1 and p2 }
JavaScript Function Syntax A JavaScript function is defined with the function keyword, followed by a functionName, and single brackets: ()
The single brackets may include a list of parameter names: (parameter1, parameter2, .....)
The code to be executed by the function is placed inside curly brackets: {}
1 2 3 function functionName(parameters) { code to be executed } The code inside the function will execute when "someone" invokes (calls) the function.
It will execute:
When an event occurs (when a user clicks a button) When it is invoked (called) from "anywhere" by JavaScript code Automatically (self invoked)
Methods:
Apply: It applies the methods of different object in the context of the calling object.
You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
if (price < 0) throw RangeError('Cannot create product "' + name + '" with a negative price'); return this; }
function Food(name, price) { Product.apply(this, arguments); this.category = 'food'; } Food.prototype = new Product();
function Toy(name, price) { Product.apply(this, arguments); this.category = 'toy'; } Toy.prototype = new Product();
var cheese = new Food('feta', 5); var fun = new Toy('robot', 40);
},
OUTPUT:
1 2 feta 5 robot 40
binds:
Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } Food.prototype = new Product();
function Toy(name, price) { Product.call(this, name, price); this.category = 'toy'; } Toy.prototype = new Product();
var cheese = new Food('feta', 5); var fun = new Toy('robot', 40); Difference between applies and call :
Apply is very similar to call, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, fun.apply(this,['eat','bananas']), or an Array object, for example,fun.apply(this,new Array('eat','bananas')).
about the writer
Manish Chauthani
Currently in Netherlands, Utrecht
find my writing online:
Search for topics with tags java, Ext js, HTML 5, Native Development on HTML 5, phonegap, sencha , sencha touch