Javascript is used to include code into a webpage.
It has elements of both object oriented(OO) and functional programming although not necessarily in a conventional way. In JavaScript, everything is an object, except for the primitive data types. We can support OO like features such as:
- inheritance: through the prototype keyword.
- encapsulation: we can provide access to an objects data using functions.
Syntax
| keywords | example | |
|---|---|---|
| Assignment | var colours = ["Red", "Green", "Blue"]; | |
Functions |
function functionname(var1,var2,...,varX)
{
some code
}
or functionname=function(){
return (2*3);
} |
|
| Call | ||
| Conditional | if (expr){statements} if (expr){statements} else {statements} if (expr){statements} else if (expr2) ... (condition) ? expression : alternative; |
|
| switch case | switch (expr) {
case SOMEVALUE:
//statements;
break;
case ANOTHERVALUE:
//statements;
break;
default:
//statements;
break;
}
|
|
| Loops | for (initial;condition;loop statement) {statements} for (var property-name in object-name) {statements} for each ... in while (condition) {statements} do {statements} while (condition); with(document) {... getElementById('x'); ...}; |
|
| Exceptions | ||
| Other reserved words | ||
Datatypes
Primitive data types:
- Undefined
- Null
- Boolean
- Number
- String
built-in objects
- Array,
- Image
- Date
- String
- Number
- Math
host objects
- window
- document
- forms
Object Oriented
We can create a single instance of an object either by:
- Create a function which does not return a value and methods are inner functions
- Or create an object and then extend it.
So we could start from a function which becomes the constructor function:
function Rectangle(width,height){
this.width = width;
this.height = height;
function getArea(){
return (this.width*this.height);
}
}
Or we could do it this way:
Rectangle=Object();
Rectangle.width=10;
Rectangle.height=20;
Rectangle.getArea=function(){
return (this.width*this.height);
}
Or we could use an object literal:
Rectangle={width:10,height:20}
We create new instances of this object by stamping out copies of it using the new keyword:
var myRectangle = new Rectangle(10,20);
Or we could modify the constructor function to become a class factory removing the need to create classes using new:
myRectangle=function(width,height){
var temp={};
temp.width = width;
temp.height = height;
temp.getArea=function(){
return (this.width*this.height);
}
return temp;
}
We can the create new instances as follows:
myRectangle2=myRectangle(30,40)
Every function/object has some private variables automatically created to support object like features:
- argument - holds an array of the arguments passed to the function.
- prototype - In every object constructor to allow you to add properties/methods to all objects created from that object constructor.
- constructor - returns the function object that created that instance of the object.
