Categories:

JavaScript Kit > JavaScript Reference > Here

Function

Last updated: January 7th, 2013

Functions in JavaScript let you define code that is called on demand, instead of immediately. There are several ways to define a function:

Standard function Statement:

function getarea(w,h){ //standard function
 var area=w*h
 return area
}

getarea(3,5) //calls function

Starting in JavaScript 1.5, you can define a function conditionally inside an if clause:

if (calculateit == true){
 function getarea(w,h){ //standard function
  var area=w*h
  return area
 }
}

Function Literal (an anonymous function assigned to a variable):

var getarea=function(w,h){
 var area=w*h
 return area
}

getarea(3,5) //calls function

Function Constructor (creates a function on the fly, which is slower and generally discouraged):

//syntax: new Function(argument1, argument2, ..., argumentY, functionbody) //all parameters must be a string

var getarea=new Function("w", "h", "var area=w*h; return area")
getarea(3,5) //calls function

Related Tutorials

Properties

Properties Description
__defineGetter__

JavaScript 1.5 feature, supported in FF, Chrome, Safari 3+, but not IE10

Method for getting the value of a property of a JavaScript object or function. In the past coders have defined their own getter and setter functions within an object to conveniently access and change data within an object- now you can do this natively and using more streamlined code.

The following defines two getter functions inside another to access the "private" properties of the later:

function getarea(width, height){
 var w = width //private prop
 var h = height //private prop

 this.__defineGetter__("w", function(){
  return w
 })

 this.__defineGetter__("h", function(){
  return h
 })

}

var house = new getarea(200, 400)
alert(house.w + " by " + house.h) // alerts "200 by 400"

When defining a getter method inside an object literal, the syntax is different, and should be in the form get functionname(){...}:

var myspace = {
 x: null,
 y: null,

 get xplusy(){
  return this.x + this.y
 },


 init:function(xval, yval){
  this.x = xval
  this.y = yval
 }
}

myspace.init(200, 500)

alert(myspace.xplusy) // alerts 700

__defineSetter__

JavaScript 1.5 feature, supported in FF, Chrome, Safari 3+, but not IE10

Method for setting the value of a property of a JavaScript object or function. Lets extend the getarea() function above with a setter method for the private variable "w":

function getarea(width, height){
 var w = width //private prop
 var h = height //private prop

 this.__defineGetter__("w", function(){
  return w
 })

 this.__defineGetter__("h", function(){
  return h
 })

 this.__defineSetter__("w", function(val){
  w = val
 })


}

var house = new getarea(200, 400)
house.w = 300 // call setter method "w" and pass 300 into its parameter
alert(house.w + " by " + house.h) // alerts "300 by 400"

As you can see, when defining a setter method, the syntax is almost identical to a getter method, with the exception that its function accepts a parameter whose value is assigned to it by you when calling it.

Getter/ Setter methods can also be defined on the prototype property of objects. The following defines a setter method on the Array object to modify the order of the array when set:

Array.prototype.__defineSetter__("sorttype", function(x){
 if (x == "alpha"){
  this.sort()
 }
 else{ // otherwise, assume sort numerically and ascending
  this.sort(function(a,b){return a -b})
 }
})

var arr = [23, 245, 54]
arr.sorttype = "alpha" // probing arr would return [23, 245, 54]
arr.sorttype = "numeric" // probing arr would return [23, 54, 245]

When defining a setter method inside an object literal, the syntax is different, and should be in the form set functionname(){...}:

var myobject = {
 a: 5,
 b: 10,
 get ab(){return this.a + this.b},
 set aplus(c){this.a = this.a + c}
}

myobject.aplus = 4 // a is now 9
myobject.ab // returns 19 (9 + 10)

arguments A local variable that points to the "arguments" object, which contains all of the arguments passed into the function. Use "arguments.length" to determine the number of arguments entered. You can use this property to define functions that accept varying number of parameters. The following function returns the sum of all of the parameters' values entered into it:

function sumof(){
 var total=0
 for (var i=0; i<arguments.length; i++){ //step through each parameter entered
  total+=arguments[i]
 }
 return total
}

//sumof(2,3,4) //returns 9
//sumof(8,7) //returns 15

The arguments object supports two properties- you already saw one of them above, which is "length". Here they are:

Properties of the arguments object
Property Description
callee References the function that is currently being called. Most commonly this property is used when you wish to have an anonymous function call itself, in which there is no function name to refer to it by. The following uses arguments.callee to create a factorial function, that is, one that accepts an integer n and returns the value 1*2*3*...*n. This is done by the function multiplying n * (n-1) and calling itself again until n reaches 1:

function(n){
 if (n<=1)
  return 1
 return n*arguments.callee(n-1)
}

You can also use arguments.callee simple to invoke the calling function when you are not privy to its name in advanced.

length Returns the number of parameters passed into the function by the user.
caller References the function in which the current function is called inside of. If the current function is called at the top level, caller returns null. You can use this property to check the context in which a function is being called. For example:

function calltest(){
 alert(calltest.caller)
}

calltest() //alerts null, as calltest() is being called at the top level

function myresidence(){
 calltest()
}

myresidence() //alerts function myresidence(), the function in which calltest() was called inside

length Returns the number of expected parameters for a function. Contrast that with arguments.length, which returns the actual number of parameters entered. The following function contains a generic check to ensure the user has entered the expected number of parameters into it:

function trianglearea(b,h){
 if (arguments.length!=trianglearea.length)
  alert("Incorrect number of parameters entered. Correct should be " + trianglearea.length)
 else
  alert(0.5*b*h)
}

trianglearea(3,8) //alerts 12
trianglearea(3,8,4) //alerts "Incorrect number of parameters entered. Correct should be 2"

prototype Lets you add custom properties and methods to a function's prototype object, which instantly adds them to all instances of the function initialized using the new operator (also called a constructor function). In the below, I'm adding a getprice() method to the constructor function Car() that is reflected on all instances of new Car():

function Car(baseprice, years_old){
 this.baseprice=baseprice
 this.history=years_old
}

Car.prototype.getprice=function(){ //add method getprice() to all instances of Car (called using new Car())
 this.price=this.baseprice - (this.history * 1000)
 alert(this.price)
}

var mytoyota=new Car(20000, 10)
mytoyota.getprice() //alerts 10,000

var myford=new Car(18000, 5)
myford.getprice() //alerts 13,000

You can also use the prototype object to extend prebuilt JavaScript objects that are initialized using the new operator with custom methods, such as with Date(), Array(), or String(). Lets extend the default String object with a backwards() method that takes a string and returns it backwards (ie: "george" becomes "egroeg"):

String.prototype.backwards=function(){
 var strlen=this.length, reversestr=''
 for (var i=strlen-1; i>-1; i--) //loop through each char within string backwards
  reversestr+=this.charAt(i)
 return reversestr
}

document.write('george'.backwards()) //writes out "egroeg"

   

Methods

Methods Description
bind(object, )

JavaScript 1.8.5 feature (currently only supported in FF4+ and Chrome 8+)

Calls a function with its scope (this object) changed to that of a different function's based on the first parameter passed into bind().
funcA.apply(funcB, [argument1, argument2, argumentN]) Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. Identical to call() below, except any arguments passed into funcA should be wrapped in an array.
funcA.call(funcB, argument1, argument2, argumentN) Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. The two methods apply() and call() are useful when you wish an object to "borrow" a method from another object and use it within its own context.

The following illustrates this:

function borrowme(name){
 this.bonus=(this.salary * 0.15) + (this.seniority * 500)
 alert(name + ", your bonus for this year is: " + this.bonus)
}

function employee(seniority, salary){
 this.seniority=seniority
 this.salary=salary
}

var employee1=new employee(10, 30000)
borrowme.call(employee1, "Sarah") //returns "Sarah, your bonus for this year is: 9500"

Here the custom object "employee" uses the function "borrowme()" to manipulate a few numbers stored within it. Normally the keyword "this" in borrowme() references just that- the function itself. However, when it''s invoked using call(), the context of "this" changes so it references the object passed into the first parameter of call(), or in this case, "employee1".

apply() and call() are important tools in implementing inheritance in JavaScript.

toString() Returns a string that represents the source code (raw text) of the function. A useful method in debugging, by looking at the source code of a function.

Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info