JavaScript - Functions, Libraries & Objects
Functions
A basic JavaScript function takes the following form:
function identifier(param1, param2,...) {
statements
}
We can also assign a function to a variable like so:
var identifier = function(param1, param2, ...){
statements
}
identifier.length
can be used inside the body of the function to determine the number of parameters.
Default Values for Parameters
For every browser apart from internet explorer we can use the following syntax:
function sum(num1 = 0, num2 = 0) {
...
}
but for internet explorer we can do the following:
function sum(num1, num2) {
if (num1 == undefined) num1 = 0
if (num2 == undefined) num2 = 0
...
}
Functions as Arguments
Functions are objects in JavaScript and can be passed to other functions:
function apply(f, x, y) {
return f(x, y)
}
function mult(x, y) {
return x * y
}
console.log('2 * 3 =', apply(mult, 2, 3))
Variable-Length Argument Lists
Every JavaScript function has an array called arguments
which consists of all the arguments passed to a function:
function sumAll() {
var sum = 0
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i]
return sum
}
Global Static Variables
We can make global static variables to preserve the value of a variable between function calls:
function counter() {
counter.count = counter.count || 0
counter.count++
return counter.count
}
document.writeln("1: static count = " + counter())
document.writeln("2: static count = " + counter())
document.writeln("3: global counter.count = " + counter.count)
1. static count = 1
2. static count = 2
3. global counter.count = 2
Nested Functions
Function definitions can be nested in JavaScript:
- Inner function have access to the variables of outer functions.
- By default, inner function can not be invoked from outside the function they are defined in.
function bubble_sort(array) {
function swap(i, j) {
var tmp = array[i]; array[i] = array[j]; array[j] = tmp;
}
if (!(array && array.constructor == Array))
throw("Argument not an array")
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length - i; j++) {
if (array[j + 1] < array[j]) swap(j, j + 1)
}
}
return array
}
JavaScript Libraries
JavaScript libraries can be imported to HTML using the following syntax:
<script src="url"></script>
Objects
Object Literals
Instead of having classes, JavaScript has object literals. They have the following syntax:
{memberName1: value1, memberName2: value2, ...}
and can look like the following:
var person1 = {
age: (30 + 2),
gender: 'male',
name: {first: 'Ben', last: 'Weston'},
interests: ['music', 'skiing'],
hello: function() {return 'Hi! I\'m ' + this.name.first + '.'}
}
Member values can be accessed using dot notation or bracket notation:
person1.age
person1['gender']
Object Constructors
We can use functions to act as object constructors like so:
function SomeObj() {
this.prop1 = 'A' // public property
var prop2 = 'B' // private property
this.method1 = function() { // public method
return 'm1[prop1 = ' + this.prop1 + ' prop2 2 = ' + prop2 + ']'
}
var method 2 = function() {...} // private method
}
obj1 = new SomeObj()
obj2 = new SomeObj()
Prototype Property
All functions have a prototype property that can hold shared object properties and methods:
- Objects do not store their own copes of these properties and methods, but only store references to a single copy.
function SomeObj() {
this.prop1 = 'A' // public property
var prop2 = 'B' // private property
SomeObj.prototype.method1 = function() {...} // public prototype
var method2 = function() {...} // private method
These can be edited during runtime to change the behaviour of a set of objects.
Class Variables & Methods
Function properties can be used to emulate Java’s class variables & methods (static variables shared among instances).
function Circle(radius { this.r = radius }
// class variable - property of the Circle constructor function
Circle.PI = 3.14159
// instance method
Circle.prototype.area = function() {
return Circle.PI * this.r * this.r;
}
// class method - property of the Circle constructor function
Circle.max = function (cx, cy) {
if (cx.r > cy.r) {return cx } else { return cy }
}
c1 = new Circle(1.0) // create an instance of the Circle class
c1.r = 2.2 // set the r instance variable
c1_area = c1.area() // invoke the area() instance method
x = Math.exp(Circle.pi) // use the PI class variable in a computation
c2 = new Circle(1.2) // create another Circle instance
bigger = Circle.max(c1, c2) // the the max class method
Private Static Variables
In order to create private static variables shared between objects we can us a self-executing anonymous function:
var Person = (function () {
var population = 0 // private static class variable
return function (value) { // constructor
population++
var name = value // private property
this.setName = function(value) {return name}
this.getName = function() {return name}
this.getPop = function() {return population}
}
}())
person1 = new Person('Peter')
person2 = new Person('James')
Pre-Defined Objects
String
A String
object encapsulates the values of the primitive datatype string
.
Properties of String
include:
length
- The number of characters in the string.
Methods of String
include:
Method | Description |
---|---|
charAt(index) |
Returns the character at position index , starting at 0. |
substring(start, end) |
Returns the part of a string between positions start and end inclusive. |
toUpperCase() |
Returns a copy of a string with all the letters in uppercase. |
toLowerCase() |
Returns a copy of a string with all letters in lowercase. |
RegExp
JavaScript supports perl-like regular expressions. String
object have methods that use regular expressions:
Method | Description |
---|---|
search(regexp) |
Matches regexp witha string and retursn the start position of the first match, or -1 if there is no match. |
match(regexp) |
Without g , returns the matching groups for the first match. With g , returns an array containing all the matches for the whole expression. Returns null if no match is found. |
replace(regexp, replacement) |
Replaces matches for regexp with replacement and returns the resulting string. |
Date
The Date
object can be used to access the local date and time.
It supports the following constructors:
new Date() // current date and time
new Date(milliseconds) // set date to unix millis
new Date(dateString) // set date according to dateString
new Date(year, month, day, hours, min, sec, msec)
Date
also provides the following methods:
Method | Description |
---|---|
toString() |
Returns a string representation of the Date object. |
getFullYear() |
Returns a four digit string representation of the current year. |
parse() |
Parses a date string and returns it in unix millis. |