Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » JavaScript » Basics of JavaScript - Part 5

Basics of JavaScript - Part 5

This article will explain, basics of JavaScript programming including Function Constructor, Literal Functions, Objects, Reference Objects, Primitive Objects, Native Objects, Instance, Generic Objects, Literal Objects, Object Properties, Object Classes, Object Methods, Instance Methods, Class Methods, String Objects, Length of Strings, Position of String, Location of String etc.]

Author Rank :
Page Views : 1079
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


HTML clipboard

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
  2.  
  3. 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)

  2. 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

     
  3. 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
     
  4. toUpperCase()

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

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

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Abhimanyu Kumar Vatsa
http://www.itorian.com/about/
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.