Javascript

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:

Syntax

  keywords example
Assignment var colours = ["Red", "Green", "Blue"];  

Functions
Objects

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:

built-in objects

host objects

Object Oriented

We can create a single instance of an object either by:

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:


metadata block
see also:

Correspondence about this page

This site may have errors. Don't use for critical systems.

Copyright (c) 1998-2023 Martin John Baker - All rights reserved - privacy policy.