Saturday 2 June 2012

Basics of Javascript4


Function Constructor

JavaScript has function constructor which allows us to create a variable and assign it a function as a value. Take a look at example

var q=new Function('a', 'b', 'return a/b;');

Function constructor takes any number of arguments, each of which must be defined as a string, and the last of which must be the body of the code for the function. This function can be invoked by the variable res=q(20,5).

Literal Functions

Function literals are similar to the function constructor except they allow us to use normal syntax to assign an anonymous function to any variable and also it has no new key. Take a look at example

var q=function
{
return a/b;
}


Objects

JavaScript is Object-based programming language but it has some feature of Object Oriented programming. JavaScript do not work the same way that they do in C++ or Java, but the similarities are more than enough to start with.

Reference Objects and Primitive Objects

Objects are composite data types. An object provides for the storage of multiple data values in a single unit. Each value is assigned a name which may then be used to reference it. Each element in an object is referred to as a property. Object properties can be seen as an unordered list of name value pairs contained within the container object.

Primitive

Primitive data type can be said to only store value. The name we use to refer to the data value refers to a set location in memory that is of a defined size and normally does not change during the executing of a program. Taking an example,

var x, y;
x = 10;
y = x;

Now if we want to see the value of y, then it will be 10. But now if we increase the value of x by 5 more then what will be the value of y.

x = x+5;

Now x must be equal to 15 but y still be equal to 10. That's because of it primitive. It's primitive does not change in general.

Reference

Reference types store a collection of references. These references are what refer to specific locations in memory. These references elements are also known as properties. Taking an example,

var x = new Object();
var y = new Object();

x.value = 10;
y=x;

Now y.value will be equal to 10. But if we increase the value of x by 5 then y will also increase it depending upon the x's value.

x.value = x.value + 5;
y.value = ? //will be 15.

Native Objects

Native objects are objects that are predefined in JavaScript. This means that we can make use of them without having to create class definition. The native objects classes are designed to save coding time by giving us most commonly used object types and related elements that we can use in our program.

Instances

Instances are just a composite data type or say object based on some rules in class definition.

var today = new Date();
var yesterday = new Date(2002,11,25);


The following two examples creating instances of the Date object. Each of them are separate instances of Date object, they can both exist in the same program. They are defined by the same object class, but each of is separate instances of that class. Besides both being of type Date they have nothing to do with each other.

Generic Objects

Using the Object keyword to create an instance of an object creates a generic object that has all the properties of an object, but no other special features. Defining a specific named class creates an object class that differs from the default Object class in the way you specify. For instance the Date object class contains predefined data fields, properties that store information about the date and time as well as methods for processing those values.

Literal Objects

As with functions and arrays, we can create object literal and constructor. A literal object is useful when we don't want to define a class of object, but want to make use of an object in a program.

var someobj = { meSay: 'how r u', youSay: 'fine' }

Working with Object's Properties

To access object properties, we use the . (dot) operator. On the left side of the period is the name of the object and on the right name of the property. Look at example

currBrowser = navigator.appName;
location.href = 'http://www.itorian.com';


When working with objects, the values are stored in the properties not in the object itself. The object is a container that is not meant to have any value in. If we try to assign a value to the object itself we will overwrite the entire object with that value. If we try to read directly from the object instance of from one of its properties, we will generate an error. If we assign a value to a property that dose not exist, then JavaScript will create that property and assign it to this instance of the object. Take a look at example,

var holiday = new Object();

holiday.NewYears = '1st January';
holiday.IndependenceDay = '15 August';
holiday.RepublicDay = '26 January';

If we try to read property that does not exist, it will return 'undefined'. Once we have properties defined, we can either access them by name or use the for….in statement to enumerate them. Here is example,

document.write(holiday.NewYears); //output will be '1st January'

for(hDate in holiday)
{
document.write(holiday[hDate]); //output will be entire
}

Object Classes

The entire premise of object oriented programming is being able to create and use our own object classes. Programmatically, a class definition is nothing but a function that creates instances of the object type as a result of it being executed. In order to define a circle, we need a centre on plane and radius. We would define the circle object like this

function Circle(x,y,r)
{
this.xCoord = x;
this.yCoord = y;
this.radius = r;
this.circum = 2*Math.PI*this.radius;
this.area = Math.PI*(this.radius*this.radius);
}


We have created an object named 'Circle' with five properties. Now to create instance of this user defined object class we use

var littleCircle = new Circle(10,10,5);

Now littleCircle is instance name and if we want to access the value we have to use

document.write(littleCircle.xCoord); //this will write x coordinate of circle
document.write(littleCircle.circum); //this will write circumference of circle


Remember, if we change the value of the circle like xCoord, yCoord and radius then the calculated value like circum and area will not be changed this is called reference type.

Object Method

Methods are functions that are associated with and invoked through objects.

Instance Methods

Instance method is one that applies only to a given instance of an object. Following is the valid use of Instance names.

var circle1 = new Circle(8, 8, 2);
var area1 = circle1.area();


In above example, circle1 is instance, Circle() is class and area is one of the method of Circle() class. We can only access to Circle() class using his instance name and method name like circle1.area(). Here is an invalid use of instance method.

var circle1 = new Circle(8, 8, 2);
var area1 = Circle.area();

In above example, we are accessing the class using class name directly that is invalid use of class. We only have to access it using instance name not the class name as we have discussed above.

Class Methods

Class method does not apply to a single instance of a class. It is invoked with the name of the class, rather than the name of the instance. The Math object is a good example of an object whose methods are class methods. We can't create an object of class Math. Math servers as a library of functions that perform calculations of numeric values. For example, to access the IP values from Math class we use

Math.PI
return (2 * Math.PI * radius);


String Object

There are some functions that can be performed on the value of primitive data types that just require that they be objects in order to work properly. The string object does have a constructor function and can be declared with it. For example,

var astring = new String('A string object');


However, JavaScript is flexible and we can declare a string with a simple assignment to a string variable and JavaScript will still let us treat it as an object. For example,

var astring = 'A string object';


Length of String

Length is an instance property that stores the number of character positions that are in the string. For example,

var astring = new String('A string object');
document.write(astring.length);
//output will be 15 (start counting from 1)

var astring = 'A string object';
document.write(astring.length);
//output will be 16 (start counting from 1)


Character Position Returning

JavaScript has two commands for returning individual characters from string as given below:

  1. charAt()

    This method returns the character at the specific index position. It takes a numeric value as an argument to specify the index position. It is an instance method. For example,

    var astring = new String('A string object');
    document.write(astring.charAt(5));
    //output will be 'i' because starts with 0
 
  1. charCodeAt()

    This method is similar to charAt() except it returns the decimal value of the character in the ASCII form. For example,

    var astring = new String('A string ojbect');
    document.write(astring.charCodeAt(12));
    //output will be 101, because 'e' has 101 ASCII value


    If we have set of character codes in ASCII form and want to convert in back in string, then we have a method named 'fromCharCode()'. fromCharCode() converts the comma separated list of decimal characters into string characters. Let's take a look

    var cstring = String.fromCharCode(72,101,108,108,111,33);
    document.write(cstring);
    //output will be 'Hello!'
Finding location of sub-strings

We have lots of JavaScript method to search sub-string (part of string) in string as given below:
  1. indexOf()

    This method is used to search the string from the beginning of the string.

    var somestring = 'this is Dog';
    ver result = somestring.indexOf('dog');
    document.write(result);
    //this will return -1 because JavaScript is case sensitive
    var result = somestring.indexOf('Dog');
    document.write(result);
    //this will return 9 (starts from 1)

  1. lastIndexOf()

    This method is used to search the string from the end of the string.

    var somestring = 'this is Dog';
    ver result = somestring.lastIndexOf('is');
    document.write(result);
    //output will be 5

     
  2. split()

    This method is used to split the string from specified location.

    var myString = "123456789";
    var mySplitResult = myString.split("5");
    document.write("The first element is " + mySplitResult[0]);
    document.write("<br /> The second element is " + mySplitResult[1]);
    //1234 and 6789 will be output consecutively

    var astring = "zero one two three four";
    var result = astring.split(" ");
    var i;
    for(i=0; i<result.length; i++)
    {
    document.write("<br>Element "+ i +" = "+result[i]);
    }
    //output will be as
    //Element 0 = zero
    //Element 1 = one and so on
     
  3. toUpperCase()

    This method will convert the string in upper case.
     
  4. toLowerCase()

    This method will convert the string in lower case.
HAVE A HAPPY CODING!

No comments:

Post a Comment