User Defined Function in Sql Server

September 24, 2007

what is user defined function???

 A UDF(user defined funtion)  is a module, which is attached to a database in Microsoft SQL Server 2000. UDF’s can accept parameters and can return a value. If you’re familiar with stored procedures, then you’ll be glad to know that UDF’s can contain code in a similar way to stored procedures. UDF’s, however are limited to modifying only local variables (those whose lifetime is within the scope of the UDF), meaning that you can’t use SELECT, INSERT, DELETE, etc statements to modify any tables outside of the scope of the UDF.

What good are UDF’s if you can’t modify relational data then? Well, they’re great for creating functions that need to work with data from databases, but don’t actually need to modify the database. You can still retrieve and manipulate tables but can’t physically commit changes to them.UDF’s support a wide range of functionality and just because you can’t commit write changes to a database, it doesn’t mean that you should turn a blind eye to them. Here’s a list of the statements that you can include in the body of a UDF:

  • Flow control statements such as IF…ELSE, CASE, GOTO labels, etc.
  • UPDATE, INSERT and DELETE commands to modify the contents of tables which are local to the UDF and have been created using SQL Server 200’s news TABLE variable type.
  • The EXECUTE command to execute stored procedures and extended stored procedures.
  • The SET and SELECT statements to assign a value to a variable.
  • SELECT statements to retrieve field values from tables into local variables.
  • CURSOR, OPEN CURSOR, CLOSE CURSOR, DEALLOCATE CURSOR and FETCH NEXT FROM statements as long as the cursor is both created and disposed of within the scope of the UDF. Note that actual rows can’t be returned, and they must be explicitly returned into type-matching variables using the FETCH NEXT INTO statement.
  • DECLARE statements to create variables local (in terms of scope) to the UDF.
  • Internally defined SQL variables which are prepended with “@@”, such as @@ERROR and @@FETCH_STATUS.

As you may’ve guessed, a UDF is in some ways similar to a stored procedure. Here’s a list of how UDF’s are different to stored procedures:

  • Scope of modification: UDF’s aren’t allowed to modify the physical state of a database using INSERT, UPDATE or DELETE statements. They can only work with local data.
  • Output parameters: UDF’s don’t have the ability to return output parameters to the calling function. They do however let us return a single scalar value or a locally created table.
  • Error handling: In UDF’s, if an error occurs during a call to a stored procedure or a trigger, then that statement is terminated and flow control continue through the UDF.
  • Calling conventions: One of the major differences between UDF’s and stored procedures is that a UDF can be called through a SQL statement without using the EXECUTE statement.

Now that we’ve got a better understanding of what a user-defined function actually is, let’s create some example UDF’s.

 In SQL Server 2000, there are three types of user-defined functions that we can create. Each one is created using SQL Server 2000’s “CREATE FUNCTION” statement, but they differ in their actual calling convention. In this section we’re going to discuss scalar functions, which can accept up to 1,024 input parameters and return one scalar (simple data type) value.Here’s the simplified signature of the “CREATE FUNCTION” statement for scalar functions:CREATE FUNCTION [ owner_name. ] function_name([ { @parameter_name [ AS ] data_type }[ ,…n ] ]

)

RETURNS data_type

[ AS ]

BEGIN

function_body

RETURN scalar_expression

END

Let’s run through the details of using the “CREATE FUNCTION” statement to create our own UDF. On the first line, we must specify the name that we want our UDF to be known as. We can also optionally specify the owner of the UDF, like this:

CREATE FUNCTION dbo.myFunction

Next, we have the optional parameter list. These are input parameters, and can be passed into our UDF from within SQL code. Here’s a parameter list that accepts two integer values and one variable character value (just like stored procedures, we can reference these input parameters in the body of our UDF):

@int1 INT,@int2 INT,@vc1 VARCHAR(50)

The RETURNS statement tells SQL Server the type of scalar variable that our function will be returning. Note that UDF’s can’t return timestamp, text, ntext or image variable types. If, for example, we wanted to specify that our UDF would return an integer, then we would use the RETURNS statement like this:

RETURNS INT

Next is the optional AS keyword, which is used to explicitly tell SQL Server where the function body starts. The actual body of our UDF is surrounded with BEGIN and END keywords, which denote a block of code in SQL Server 2000:

BEGIN— Body of our UDF goes here— RETURN statement and value go here

END

Lastly, we have the RETURN statement, which allows us to return a value back to whoever called our UDF. The value after the RETURN keyword should be of the same type as the keyword specified after the “RETURNS” statement earlier in the “CREATE FUNCTION” statement:

CREATE FUNCTION dbo.myFunction()RETURNS INT

AS

BEGIN

DECLARE @myInt INT

SET @myInt = 1

— Function body goes here

RETURN @myInt

END

As you can see in the example above, we have told SQL Server that our UDF will return an integer type using the “RETURNS INT” statement. In the actual body of our UDF, the “RETURN @myInt” statement returns the value of the declared integer variable, @myInt, which is 1.

Let’s create a simple user-defined function that will multiply two numbers together and return that number as its result. Open Query Analyzer (Start -> Programs -> Microsoft SQL Server -> Query Analyzer) and connect to your database with administrative rights.

Enter and execute the following code in the query analyzer window (I will assume that you will be creating your UDF’s under the “pubs” database, which is a default database that comes pre-installed with SQL Server 2000):

USE PUBSGOCREATE FUNCTION dbo.mult

(

@num1 INT,

@num2 INT

)

RETURNS INT

AS

BEGIN

RETURN (@num1 * @num2)

END

Our new function, named “mult”, accepts two integer values and returns the product of those two values. To test our UDF, delete all of the code in the query window and enter the following code:

USE PUBSGODECLARE @result INT

SET @result = dbo.mult(5, 10)

PRINT @result

Output into the results window should look like this:

The result of executing our scalar UDF

You’ll notice that I’ve called our scalar UDF using a two-part name in the form of ownerName.functionName. I could’ve also used a three-part name in the form of databaseName.ownerName.functionName such as “PUBS.dbo.mult”. Using a two/three part name to call our UDF is mandatory and helps SQL Server 2000 to distinguish between our UDF’s and system level functions.

Next we can try with inline-statement and multiline statement table valued UDF.

thanks:)

Triggers in Sql server 2005

September 21, 2007

A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure.” If you’re a developer and not familiar with triggers this article is a great starting point.

A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure. As a matter of fact, triggers are often referred to as a “special kind of stored procedure.” The main difference between a trigger and a stored procedure is that the former is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created.The following shows how to create a trigger that displays the current system time when a row is inserted into the table to which it is attached.

SET NOCOUNT ON
CREATE TABLE Source (Sou_ID int IDENTITY, Sou_Desc varchar(10))
go
CREATE TRIGGER tr_Source_INSERT
ON Source
FOR INSERT
AS
PRINT GETDATE()
go
INSERT Source (Sou_Desc) VALUES ('Test 1')
-- Results --
Apr 28 2001  9:56AM

This example is shown for illustrative purposes only. I’ll cover an example later in the article that shows a real-world world use of triggers.

When to Use Triggers

There are more than a handful of developers who are not real clear when triggers should be used. I only use them when I need to perform a certain action as a result of an INSERT, UPDATE or DELETE and ad hoc SQL (aka SQL Passthrough) is used. I implement most of my data manipulation code via stored procedures and when you do this the trigger functionality can be moved into the procedure. For example, let’s say you want to send an email to the Sales Manager when an order is entered whose priority is high. When ad hoc SQL is used to insert the Orders row, a trigger is used to determine the OrderPriority and send the email when the criteria is met. The following shows a partial code listing of what this looks like.

CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10))
go
CREATE TRIGGER tr_Orders_INSERT
ON Orders
FOR INSERT
AS
IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1
BEGIN
PRINT 'Email Code Goes Here'
END
go
INSERT Orders (Ord_Priority) VALUES ('High')
-- Results --
Email Code Goes Here

When the stored procedure approach is used you can move the trigger code into the procedure and it looks like this.

CREATE PROCEDURE ps_Orders_INSERT @Ord_Priority varchar(10)
AS
BEGIN TRANSACTION
INSERT Orders (Ord_Priority) VALUES (@Ord_Priority)
IF @@ERROR <> 0
GOTO ErrorCode
IF @Ord_Priority = 'High'
PRINT 'Email Code Goes Here'
COMMIT TRANSACTION
ErrorCode:
IF @@TRANCOUNT <> 0
PRINT 'Error Code' go

Let’s take a look at the trigger example. The first thing you probably noticed is that the SELECT references a table called inserted. Triggers make use of two special tables called inserted and deleted. The inserted table contains the data referenced in an INSERT before it is actually committed to the database. The deleted table contains the data in the underlying table referenced in a DELETE before it is actually removed from the database. When an UPDATE is issued both tables are used. More specifically, the new data referenced in the UPDATE statement is contained in inserted and the data that is being updated is contained in deleted.

The example makes an assumption about how data is going to be added to the table. The IF statement is looking for a count of 1. This means the trigger assumes only one row will be added to the table at a time. If more than one row is added to the table in a single statement you may miss an order with a High priority because the trigger only fires once for each associated statement. I realize this may sound a little confusing so let’s take a look at two more examples. The following shows that the trigger fires for each INSERT statement executed.

INSERT Orders (Ord_Priority) VALUES ('High')
INSERT Orders (Ord_Priority) VALUES ('High')
-- Results --
Email Code Goes Here
Email Code Goes Here

Now we have three rows in Orders whose Ord_Priority is High. Let’s insert new rows based on the current contents of Orders to show how a trigger behaves when a multi-row statement is executed.

INSERT Orders SELECT Ord_Priority FROM Orders

The ‘Email Code Here’ message is not displayed even though three new rows were added with a priority of High because the IF statement criteria was not satisfied. A trigger fires only once per statement, so the actual COUNT(*) associated with the INSERT is 3. The following shows how to modify the code to handle a multi-row INSERT.

ALTER TRIGGER tr_Orders_INSERT
ON Orders
FOR INSERT
AS
IF EXISTS (SELECT * FROM inserted WHERE Ord_Priority = 'High')
BEGIN
DECLARE @Count tinyint
SET @Count = (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High')
PRINT CAST(@Count as varchar(3))+' row(s) with a priority of High were entered'
END
go

We can test the code using the same INSERT with a SELECT as follows.

INSERT Orders SELECT Ord_Priority
FROM Orders
-- Results --
12 row(s) with a priority of High were entered

A Real-World Example

Those of you familiar with web site management know that counting the traffic on a site is key in determining which areas of the site are being used. Internet Information Server (IIS) has logging capabilities that tracks a number of attributes associated with each visitor. For example, every time a visitor accesses a page on a site that page and the user’s information is logged. By default the data is logged in a text file, but you can alter the default behavior and log the data to an ODBC-compliant data store.

I used this approach for a client a while back because they wanted a simple way to track the activity for each major area of their site. A major area was defined as the sections listed on the site’s main navigation bar (e.g., Home, About Us, Services, …). The goal was to produce a report that showed the number of visits to each of the main areas of the site on a per month basis. A few of you may be wondering why a trigger is needed to implement this solution. After all, a SELECT with a WHERE clause to filter the date range and GROUP BY to count the instances per page will do the trick and no triggers are needed.

The reason I decided to use a trigger-based solution had to do with the unacceptable execution time of the report. Even on a low-traffic site the number of rows in the logging table grows at a staggering rate. For every page accessed by a visitor, there is at least one row added to the table. When a page contains a reference to a graphic (e.g., .gifs or .jpgs), there is another row created. If a page contains five references to graphics, there are six rows created in the logging table every time it is accessed.

The bottom-line is that because of the size of the table the report took too long to execute. In order to reduce the time it took to execute the report I decided to use a summary (aka aggregate) table to count the page views as they were entered into the logging table. Since there were only eight main areas on the site, the summary table contained eight rows and the report ran in less than one second.

The following uses a dummied-down schema to show how this technique works. For the sake of brevity, I will only use two main areas of the site.

CREATE TABLE InetLog (ClientHost varchar(255), LogTime datetime, Target  varchar(255))
go
CREATE TABLE LogSummary (LogSum_Category varchar(30), LogSum_Count int)
go
INSERT LogSummary VALUES ('About Us',0)
INSERT LogSummary VALUES ('Services',0)

InetLog is the main logging table and LogSummary is the summary table. The two main areas of the site are About Us and Services. The goal of the trigger is to update the value in LogSum_Count every time the AboutUs.htm and Services.htm pages are accessed. The trigger used to do this is shown here.

CREATE TRIGGER tr_InetLog_INSERT
ON InetLog
FOR INSERT
AS
IF EXISTS (SELECT * FROM inserted WHERE Target = 'AboutUs.htm')
BEGIN
UPDATE LogSummary
SET LogSum_Count = (SELECT COUNT(*) FROM InetLog WHERE Target = 'AboutUs.htm')
WHERE LogSum_Category = 'About Us'
END
IF EXISTS (SELECT * FROM inserted WHERE Target = 'Services.htm')
BEGIN
UPDATE LogSummary
SET LogSum_Count = (SELECT COUNT(*) FROM InetLog WHERE Target = 'Services.htm')
WHERE LogSum_Category = 'Services'
END
go

The trigger simply extends on the examples presented earlier and when the IF criteria is met the associated row in LogSummary is updated. The following shows the trigger works as expected.

INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:00:50','Default.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:01:01','AboutUs.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:02:01','Services.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:03:01','Products.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:04:50','Default.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:05:01','AboutUs.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:06:01','Services.htm')
INSERT InetLog VALUES ('111.111.111.111', '4/1/29 12:07:01','Products.htm')
go
SELECT * FROM LogSummary
-- Results --
LogSum_Category------------LogSum_Count
About Us 2 Services 2

UPDATE Trigger

An UPDATE trigger is used to perform an action after an update is made on a table.The example shown here is based on the table used in this article.

CREATE TRIGGER tr_Orders_UPDATE
ON Orders
AFTER UPDATE
AS
 
--Make sure Priority was changed
IF NOT UPDATE(Ord_Priority)
 RETURN
 
--Determine if Priority was changed to high
IF EXISTS (SELECT *
           FROM inserted a
                  JOIN deleted b ON a.Ord_ID=b.Ord_ID
                  WHERE b.Ord_Priority <> 'High' AND
                  a.Ord_Priority = 'High')
 BEGIN
  DECLARE @Count tinyint
  SET @Count = (SELECT COUNT(*)
                FROM inserted a
                               JOIN deleted b ON a.Ord_ID=b.Ord_ID
                               WHERE b.Ord_Priority <> 'High' AND
                               a.Ord_Priority = 'High')
  PRINT CAST(@Count as varchar(3))+' row(s) where changed to a priority of High'
 END
go

In Part I the INSERT trigger watched for orders with a priority of ‘High.’ The UPDATEtrigger watches for orders whose priority are changed from something else to High.The IF statement checks to see if the Ord_Priority value was changed. If not we cansave some time by exiting the trigger immediately.The deleted table holds the pre-UPDATE values and inserted table holds the new values.When the tables are joined it is easy to tell when the priority changes from somethingelse to High.

DELETE Trigger

Once you understand how an UPDATE trigger works a DELETE trigger is easy to implement.In the example shown here it simply counts the number of rows in the deleted table to see how many had a priority of high.

CREATE TRIGGER tr_Orders_DELETE
ON Orders
AFTER DELETE
AS
 
--Determine if Order with a Priority of High was deleted
IF EXISTS (SELECT * FROM deleted WHERE Ord_Priority = 'High')
 BEGIN
  DECLARE @Count tinyint
  SET @Count = (SELECT * FROM deleted WHERE Ord_Priority = 'High')
  PRINT CAST(@Count as varchar(3))+' row(s) where deleted whose priority was High'
 END
go
 

INSTEAD OF Triggers

INSTEAD OF triggers are new to SQL Server 2000. The main reason they were introduced is to

facilitate updating Views. I am going to show you how one works, but I am not going to

bother with updating a View. Quite frankly I think updating Views is poor application design.

I was once told by one of my editors that some of my views on Views reflect my “insular”

experience, so if you do not agree with me on this point rest assured you are not alone.

An INSTEAD OF Trigger is used to perform an action instead of the one that caused the trigger to be fired. This sounds like double-talk, so I will explain a little more. Let’s say you have an INSTEAD OF INSERT trigger defined on a table and an INSERT is executed. A row is not added to the table, but the code in the trigger is fired. The following shows what this looks like.

CREATE TRIGGER tr_Orders_INSERT_InsteadOf
ON Orders
INSTEAD OF INSERT
AS
PRINT 'Updateable Views are Messy'
go

The following INSERT produces the message shown, but the row is not added to the table.

INSERT Orders (Ord_Priority) VALUES ('High')
 
-- Results --
 
Updateable Views are Messy

Feel free to experiment with this type of trigger, but unless you are trying to update a View that is based on multiple tables I do not think it will be of much practical value Before I leave this section I must mention that this homemade solution is not the referred way to monitor web site traffic. I certainly had fun researching ODBC-logging and writing the code, but I actually suggested the client buy a commercial software package like Trends to implement this functionality. WebTrends is a great product and allows you to perform detailed analysis of a site’s traffic. The client did not want to spend any money onreal software, but instead on me:))

thanks:)

Database Management System Vs File Management System

September 21, 2007

A Database Management System (DMS) is a combination of computer software, hardware, and information designed to electronically manipulate data via computer processing. Two types of database management systems are DBMS’s and FMS’s. In simple terms, a File Management System (FMS) is a Database Management System that allows access to single files or tables at a time. FMS’s accommodate flat files that have no relation to other files. The FMS was the predecessor for the Database Management System (DBMS), which allows access to multiple files or tables at a time (see Figure 1 below)

comparison.jpg

File Management Systems

Advantages Disadvantages

Simpler to use

Typically does not support multi-user access

Less expensive·

Limited to smaller databases

Fits the needs of many small businesses and home users

Limited functionality (i.e. no support for complicated transactions, recovery, etc.)

Popular FMS’s are packaged along with the operating systems of personal computers (i.e. Microsoft Cardfile and Microsoft Works)

Decentralization of data

Good for database solutions for hand held devices such as Palm Pilot

Redundancy and Integrity issues

Typically, File Management Systems provide the following advantages and disadvantages: 

The goals of a File Management System can be summarized as follows (Calleri, 2001):

  • Data Management.  An FMS should provide data management services to the application.
  • Generality with respect to storage devices. The FMS data abstractions and access methods should remain unchanged irrespective of the devices involved in data storage.
  • Validity. An FMS should guarantee that at any given moment the stored data reflect the operations performed on them.
  • Protection. Illegal or potentially dangerous operations on the data should be controlled by the FMS.
  • Concurrency. In multiprogramming systems, concurrent access to the data should be allowed with minimal differences.
  • Performance. Compromise data access speed and data transfer rate with functionality.

From the point of view of an end user (or application) an FMS typically provides the following functionalities (Calleri, 2001): 

  • File creation, modification and deletion.
  • Ownership of files and access control on the basis of ownership permissions.
  • Facilities to structure data within files (predefined record formats, etc).
  • Facilities for maintaining data redundancies against technical failure (back-ups, disk mirroring, etc.).
  • Logical identification and structuring of the data, via file names and hierarchical directory structures.

Database Management Systems

Database Management Systems provide the following advantages and disadvantages: 

Advantages

Disadvantages

Greater flexibility

Difficult to learn

Good for larger databases

Packaged separately from the operating system (i.e. Oracle, Microsoft Access, Lotus/IBM Approach, Borland Paradox, Claris FileMaker Pro)

Greater processing power

Slower processing speeds

Fits the needs of many medium to large-sized organizations

Requires skilled administrators

Storage for all relevant data

Expensive

Provides user views relevant to tasks performed

 

Ensures data integrity by managing transactions (ACID test = atomicity, consistency, isolation, durability)  

 

Supports simultaneous access 

 

Enforces design criteria in relation to data format and structure 

 

Provides backup and recovery controls

 

Advanced security

 

The goals of a Database Management System can be summarized as follows (Connelly, Begg, and Strachan, 1999, pps. 54 – 60): 

  • Data storage, retrieval, and update (while hiding the internal physical implementation details)
  • A user-accessible catalog
  • Transaction support
  • Concurrency control services (multi-user update functionality)
  • Recovery services (damaged database must be returned to a consistent state)
  • Authorization services (security)
  • Support for data communication Integrity services (i.e. constraints)
  • Services to promote data independence
  • Utility services (i.e. importing, monitoring, performance, record deletion, etc.)

The components to facilitate the goals of a DBMS may include the following:

  • Query processor
  • Data Manipulation Language preprocessor
  • Database manager (software components to include authorization control, command processor, integrity checker, query optimizer, transaction manager, scheduler, recovery manager, and buffer manager)
  • Data Definition Language compiler
  • File manager
  • Catalog manager

thanks:)

Abstract Classes Vs Interfaces

September 18, 2007

When does it make sense to choose an abstract class over an interface?

In Java, under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them?

Ans:Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the Java language and object-oriented programming in general

Yes, other nonabstract methods can access a method that you declare as abstract.

But first, let’s look at when to use normal class definitions and when to use interfaces. Then I’ll tackle abstract classes.

Class vs. interface

Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.

For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don’t want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.

With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let’s call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you’ll need some plumbing to properly instantiate the algorithm strategies you will need.

This is an excellent place to use an interface. We’ve used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn’t allow multiple inheritance, so you can’t extend something that gives you a useful implementation or more type identity.

Interface vs. abstract class

Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn’t know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They’re also a good choice for nonleaf classes in class hierarchies.

thanks:)

WEB 2.0(Some Important Points)

September 18, 2007

Recently we entered into the world of web 2.0, So here are some features of web2.0 which has some advantage over the old version of web.

What it is, what it’s not, and some ideas for

moving forward into the Web 2.0 world

 

• There are a myriad of definitions and explanations of Web

2.0 in the industry; this topic discusses some

aspects of the most common definitions

• Web 2.0 is an evolution in process; what it is today may

be different from what it is tomorrow

 

What is Web 2.0?

Web 1.0 was commerce;

Web 2.0 is people.

A slightly longer definition …

Web 1.0 was about connecting computers

and making technology

more efficient for computers.

Web 2.0 is about connecting people,

and making technology for efficient for people

 

Some basic advantage of web2.0 over web1.0 they are as follows:

 

Syndication: focus on disseminating content

Stickiness: focus on driving users to –> from the site out to the interested parties

the site and keeping them there

tagging (“folksonomy”): the users of the web

site decide how they think the information fits

into their worldview

directories (taxonomy): the web site

creator decided how the information

was organized

MySpace: a common place to go where

everybody is (or can be) your friend; allows you

to post your photos, videos, music, blogs

personal websites: individually

created and maintained web sites with

unique URLs

Wikipedia: allows users to read, write, update

Britannica Online: published –> and delete encyclopedia entries on the web

encyclopedic information on the web

Flickr: allows users to securely manage and

Ofoto: allows users to upload their –> share their photos in an online space

digital photos and get printouts

Google Maps: same capabilities but uses Ajax

to provide the user with a smoother, faster

experience; no waiting for an HTTP request

Mapquest: presented the visitor with a

static view of a map; provided zoom

capabilities

 

What is Web 2.0? An extended definition

Web 2.0 is the network as platform, spanning all connected

devices; Web 2.0 applications are those that make the most of

the intrinsic advantages of that platform: delivering software

as a continually-updated service that gets better the more

people use it, consuming and remixing data from multiple

sources, including individual users, while providing their own

data and services in a form that allows remixing by others,

creating network effects through an “architecture of

participation,” and going beyond the page metaphor of Web

1.0 to deliver rich user experiences.

 

Characteristics of Web 2.0

• Participatory and

Collaborative

• Data and Services

• Responsive

Experimentation

• Joy of Use

• Mobility

• Business Model Evolution

 

Participatory and collaborative: Description

• Participatory: affording the opportunity for individual participation1

– The traditional web has tended to be one-sided, with a flow of content

from provider to viewer; with Web 2.0, the flow is 2-way

• Barometers: Comment on this page, Rate this page

• Blogs: (or weblog) is a website in which items are posted and displayed with the

newest at the top; blogs often focus on a particular subject2

• Creating/publishing original content

• Collaborative: To work together, especially in a joint intellectual effort3

– Allow our visitors not just to participate, but also to help shape their

visitor experience and our web site. Examples include:

• Wikis: a type of website that allows anyone visiting the site to add, remove, or

otherwise edit all content, very quickly and easily2

• Folksonomies: content is categorized using a familiar, accessible, and shared

(community) vocabulary

 

Participatory and collaborative: In actionWikis:

Used where they make sense, wikis can be a powerful source of information for an

organisation about their visitors, as well as a powerful tool for the visitor to be

successful in their task on at a site. For example:

– How to best work with a company

– Creative uses for “tips ‘n tricks”

– Allow users to participate in the information provided by a company (“making it their own”)

– Main or task-based navigation pages would not be optimal candidates

Barometers:

Comment on this page, rate this product/service, tell-a-friend, etc.

– Comment on this page:

• Provide “free-form” textual comments/suggestions about selected pages or applications on the site.

• Enables the end-user to influence what we present on our pages or determine how our applications

should/could work

– Ratings: collect ratings and use them to influence navigation by featuring articles with good ratings on

homepages or showing ratings on the page (1-5 Stars)

– Related information: Suggested links based on user contributions (explicit) or based on clickstream

analysis (“customers who are interested in this also…”)

 

Data in the Web 2.0 world: Description

Data Access: Surfacing the data to the visitor

– Content Syndication is one way of bringing the right information to the right people at

the right time

– Navigation becomes driven by the data itself; rather than solely by a predefined path

chosen by the web site creator

– Where appropriate, Content Management revolves around lower level components of

data, rather than pages of data

Data Sources

– Sources are no longer strictly internal to a company

– Licensed data and data bases are the norm

– Data is continually enriched by the client themselves, explicitly, or by our observations

of their actions, implicitly

Data State

– “Remixing” the data allows for a richer visitor experience; one partially driven by the

visitor themselves

• Enable other people to put together their own experiences from our data

– Having access to the right data is not enough; adding value to the data will be a business

differentiator

 

Data in the Web 2.0 world: In action

• A Content Backbone accessible via data display and distribution services is a

fundamental component, with the following elements:

– Enterprise Content Management supplemented by a runtime repository

– Structured Taxonomies working in conjunction with “Folksonomies”

– Dynamic assembly of content components for personalized and destination pages

– Dynamic Navigation driven by a modern search engine will enable access to the desired content

• RSS Feeds: RSS feeds can deliver both data to people and data to a screen for

people to view

– Enable the Homepage as an RSS feed

– Enable brand and audience pages to serve content from RSS feeds

• Ensure up-to-the-minute data is available for Mashups1 like product comparison

shopping services

• Standards are key…. XML, RSS, Micro-formats

1 A mashup, according to http://www.wikipedia.com, is a website or web application that combines content

from more than one source

 

Web Services in the Web 2.0 world: Description

• Web architecture evolves to provide a richer client experience through the use

of web services

– Web Services are built as lightweight, flexible, specific use applications; not as

monolithic end-to-end software solutions

– Software is built as a web service to be purchased or used for a single purpose

– Data itself becomes almost inseparable from the web service being offered

An example of a simple web service is a weather service. Request data based

on longitude, latitude and other factors such as maybe date, and get data returned

Activity Planner

Aggregates weather and

other data to make activity

recommendations.

 

Web Services: In action

• Distributed Content Modules which leverage multiple data

sources through services

– Distributed Personalization: enabled through identity services

– Dynamic Related Links, Syndicated Search (OpenSearch

RSS)

• Shipping status (DHL, UPS, FedEx…)

• Stock Price Data

• Commerce Solutions

• Outsourced Search

 

Web Services: Technology considerations

• Content as a service

• Generate content fragments in structured formats (XML)

• Remove the burden from content management systems and Web

applications to generate HTML

• Application programming interfaces (APIs)

– Documented and supported APIs

– Based on SOAP, REST (XML over HTTP), RSS and ATOM

• Security

– Access to personal and protected information and access control mechanisms

must be implemented server-side

– Application to application communication authenticated with certificates

– Third party access to APIs secured with tokens (requires registry)

• Services are easy to use, but not necessarily easy to build

 

Responsive experimentation: Description

• Carve out small pieces of function on which to iterate,

continually evaluate the effectiveness of that function,

and make business decisions based on the evaluation

• Experiment and continuously improve both existing

and new features and function

• New services will be Beta and declared Beta publicly

until matured

• Sampling of audience to try out new services

• Small and simple components

• Experimentation does not mean poor quality

–Built on solid architecture and infrastructure

–Documented and supported APIs

–Easy to use and integrate with other Web 2.0 applications for

customers and developers

–Configure the experience, rather than code it

Iterate

Decide

Evaluate

David Leip

Responsive experimentation: In action

• Innovation pilots and betas: Personalisation, Wikis, Blogs,

etc.

• Utilize small, controlled environments for pilots

– Portions of the web site: segment the audience to try out new

features and function

– Target one customer or one account and get feedback

• Use of Agile Methodologies: Allows for rapid iteration of

development cycles

• Sense and Respond Metrics: Create valid business metrics to

enable rapid response to changes in visitor behavior or overall

site trends

• Easy to use feedback mechanisms: Facilitate the capture of

visitor feedback

 

Joy of use: DescriptionGenerate Buzz and Delight the Visitor

– Do things that customers like and media

talks about

• The business value of Google Maps may not

have been immediately obvious, but it did get

a lot of attention

– Utilize cool and innovative technologies

to enhance the visitor experience

• Add real value to the user experience but also

have a “wow factor”

More importantly, empower others

– There is only so much we can do

ourselves

– Others may have ideas what to do with

our data in ways we have not even

thought about.

– Allow and enable others to do “cool

stuff” with our assets

 

Joy of use: In Action

• WebCams and VoIP

– The ability to click a link on the website which opens a

dialogue with a live person over the web (either voice or

voice and visual)

• Product Viewing and Assistance

– Servers: 360o view to show you how to set up and configure a

product

• RSS aggregation

– Give visitors the ability to view all of their RSS feeds in one

place

 

Mobility in the Web 2.0 world: Description

• What Mobility means

– Software and services that operate on

multiple devices in a way that is

transparent to the user

– Content that is accessible to the user

regardless of the device used

– Being prepared for the next wave of

devices, as yet unknown

 

Mobility in the Web 2.0 world: In action

• Enhance existing functions to be accessible from the wireless devices

– Drive traffic to the mobile version of the applications through awareness and auto redirects

– Provide fast access through Search to a wide variety of content from any device

– Short URLs and easy navigation very important

• Use 2D barcodes in advertising and direct marketing materials to drive Web

traffic

– Customers who see an ad in a magazine or on a billboard, or receive direct marketing

material, can point their mobile phone to the 2D barcode and access the related Web site

directly without typing lengthy URL addresses

• Provide more syndicated content for site visitors

– Allow the visitors to take away pieces of your content and explore them at a time of their own

choosing (audio or video podcasts, RSS feeds, etc.)

• Automatic Alerts to the cell phone to notify the client of key events:

– Their order has shipped

– A proposal is ready for their review

– Payment has been received

 

Business model evolution: DescriptionCustomer interaction changes

– The web site becomes but one way to do business with company on the web

– Customers may never come to the company Web site

– Interaction is two-way and collaborative through various tools

Content and applications change

– Open access to selected content assets and applications

– Integration of third party content and user provided information assets

Measuring success changes

– Measuring impressions, click-throughs, and conversions becomes more of a challenge

• Impressions for an RSS feed might the number of subscriptions … but what is a click-through? A

conversion?

• What is the business value of a visitor contributing to a Wiki?

• Revenue and market share: more conversions is the goal … but how do you measure a

conversion on a business partner’s web site or a comparison shopper’s mashup?

• Most companies sell products and services, not page views or Podcasts or RSS feeds … how do

we relate these things to opportunities?

 

Business model evolution: In actionBusiness Enablement

– RSS Feeds and podcasts as communications vehicles

– Function delivered to the client, rather than coming to the site

– Use Web 2.0 tools and concepts to innovate with value partners (clients, BPs, etc.)

Content Enablement

– Ensuring that the right content is available in the right places

– Mashups, Wikis, Blogs, Folksonomies, etc. all contribute to bringing in data from other

sources to enhance the value of the site and fostering collaboration between a company

and its value partners

Metrics Enablement

– Validate and track goal, family, and role definitions

– Comprehensive, site-wide measurements of content, page and site value to visitor

– Continuously assess the quality of site navigation

– Segment metrics by industry, by other profile attributes, and by account

– Account segmentation allows questions like “What is a given client thinking about?”

– New ways to measure OO, OI, and OD

• OD = Opportunity Discovery, e.g. notify account rep that “Client X is

investigating CRM”

 

Tech considerations: Moving into the Web 2.0 world

Web 2.0 server infrastructure has some challenges

􀂃 Web 2.0 technologies work best on a single logical Web server (Ajax and

XLST work in a subdomain/domain, depending on browser)

􀂃 One approach is the integration of multiple Web hosting infrastructures under a

single ”front-end”

􀂃 Globally mirrored infrastructure to reduce latency

AJAX applications

􀂃 Augment user interaction and enable highly interactive, desktop-like

applications

􀂃 Usually require large initial download and frequent network interactions

􀂃 Alternate implementation required for non-JavaScript access (Accessibility,

Search engine crawlers)

 

web2.0 is for public then what will be for web 3.0….??

 

thanks:)

CSS in Web Pages

August 20, 2007

THE 3 WAYS TO INSERT CSS INTO YOUR WEB PAGES

For some of you, this may sound like a real lame article. But you ought to give it a chance because I don’t write about stuff you’ll never use! I avoid marginal, nerd centric ivory tower blather like a cat avoids water.

I’ve read hundreds (sadly, this is true) of those 2-inch thick nerd books (I don’t get out much) and I can’t stand it when people waste paper on that kind of generally useless stuff. So read on, eager student, and you will be well on your way to building your own killer web sites!

🙂

The wise people who created CSS came up with 3 basic ways for you to use CSS in your web pages:

1. With an external file that you link to in your web page:

<link href=”myCSSfile.css” rel=”stylesheet” type=”text/css” />

or using the import method:

<style type= “text/css ” media= “all “>

@import “myCSSfile.css “;

</style>

Why use the import method versus the link method when using external style sheets? Use the import method if you want to support really old browsers like Netscape 4.0.

Let me explain: Netscape can’t handle most CSS beyond font settings and colors, if it finds any other types of CSS it could cause good old Netscape 4 to crash in some occasions or at the very least mangle your page.

Netscape 4 does not understand the @import method of linking to a style sheet like the newer browsers can, so Netscape just ignores it. You can use this to hide the fancy CCS code in the external style sheet by using the @import method so all the good browsers can reference it while keeping Netscape 4 out of the picture.

Netscape 4.0 is pretty much dead (that is really a good thing) so I personally don’t worry much about it. But for some of you, it may be of concern so I thought it should be mentioned.

2. By creating a CSS block in the web page itself; typically inserted at the top of the web page in between the <head> and </head> tags:

<head>

<style>

p { padding-bottom:12px; }

</style>

</head>

3. by inserting the CSS code right on the tag itself:

<p style= “padding-bottom:12px; “> Your Text</p>

So some of you may be asking why have the 3 methods of including the CSS in a web page? The answer is: flexibility and laziness! Ok I’m kidding about the laziness, replace it with ‘precision’. So what the heck does that mean?

I think the easiest way to explain to you what’s going on, is by giving you real examples that demonstrate the differences. Wait a second, don’t fall asleep … the examples are short and I think that once you finish, you will see how easy it really is!

Another reason that you want to continue reading this article is that you will gain a good understanding of some fundamental (and practical) CSS principles – remember that the difference between people who are really good at what they do, and those who are not so good, is in the mastery of the basics. Lets get down on it!

Method 1: Create a separate CSS file and link it to your web page(s)

The heading for this part of the article hints at why you would want to go through the trouble of creating a separate CSS file instead of just typing in the CSS code in the web page itself. Can you guess? Keep trying … times up! Did you get it? I could quote you some nerd centric description that describes the advantage; the problem is that only nerds who already know would understand!

In a nutshell: by keeping the CSS code in its own file, you can link that CSS file to as many web pages as you want. This has two major advantages:

  1. You will have much less code in all your HTML pages – makes the pages neater and easier to manage and makes the web pages a little faster on the download. (Although this point is really minor in most cases, and is really over blown in my opinion by some people)
  2. It can potentially reduce the amount of work you have to do in a big way. Why you ask? Simple; lets say you have 50 web pages where you’ve set the text to be black and the headline text (text in between the <h3> tags for example) to blue. Then one day you decide you want to change the color of the text. Since the CSS that controls the text color for the 50 pages is in one CSS file, you can easily change the color of your text in all 50 pages by changing one line in the CSS file!

If on the other hand you had decided to include all your font color information in each page, you would have had to change all 50 pages. This would have been even worse if you had been using font tags, or CSS right on each tag, you would have to change the color settings/code on all the <p> and <h3> tags in all 50 pages! I can tell you from experience that that sucks big time!

The rule:

If you are going to have more than one web page with the same stylistic properties (that look the same in some way) you should create a separate CSS file and link your web pages to it.

Method 2: Create a CSS block in the web page itself

The Rule:

Use this method if you want to override the CSS you have in a linked CSS file or if you only have a one-page web site.

Now that we covered the first method of putting all your CSS code in a separate file and linking to it, the other methods are easy to describe.

CSS stands for (is the acronym for): ‘Cascading Style Sheets.’ I think the words ‘style sheets’ in CSS are self-describing … we know what ‘style’ in style sheets mean. But what is the meaning of ‘cascading’ in CSS?

The cascading effect in CSS

The word ‘cascading’ in CSS describes a cascading mechanism; that is to say that the CSS code on the page itself will override the CSS code in a separate linked file. And subsequently, CSS declared ‘inline’ on the tag itself would override all other CSS.

So let’s look a practical example; let’s say you have a web site with 50 pages where the layout and fonts are the same on all 50 pages. Wisely you put the CSS information that sets the layout and font choices in a separate style sheet, but for a particular page you need to change the color of some of the text and add a border around a paragraph. This is a perfect example where you might want to place a little CSS in the page itself since the color and border will be unique to that page. Is this all sinking in? 🙂

Method 3: Embed the CSS right on the tags themselves (called inline CSS)

The Rule:

Use this method on a unique element/tag that you want to affect with CSS.

An example can be with a special heading on the page where you want to have a little more padding than you typically do for a heading. Instead of creating a class elsewhere that will only be used on this one occasion, it makes sense to me to just include the CSS inline. I have to stress that inline CSS is something you should rarely if ever use because it can get messy quick.

thanks 🙂

CSS for the Beginners

August 20, 2007

AN INTRODUCTION TO CASCADING STYLE SHEETS

CSS is the acronym for: ‘Cascading Style Sheets’. CSS is an extension to basic HTML that allows you to style your web pages.

An example of a style change would be to make words bold. In standard HTML you would use the <b> tag like so:

<b>make me bold</b>

This works fine, and there is nothing wrong with it per se, except that now if you wanted to say change all your text that you initially made bold to underlined, you would have to go to every spot in the page and change the tag.

Another disadvantage can be found in this example: say you wanted to make the above text bold, make the font style Verdanna and change its color to red, you would need a lot of code wrapped around the text:

<font color=”#FF0000″ face=”Verdana, Arial, Helvetica, sans-serif”><strong>This is text</strong></font>

This is verbose and contributes to making you HTML messy. With CSS, you can create a custom style elsewhere and set all its properties, give it a unique name and then ‘tag’ your HTML to apply these stylistic properties:

<p class=”myNewStyle”>My CSS styled text</p>

And in between the <head></head> tags at the top of your web page you would insert this CSS code that defines the style we just applied:

<style type=”text/css”>
<!–
.myNewStyle {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-weight: bold;
color: #FF0000;
}
–>
</style>

In the above example we include the style sheet code inline, or in other words, in the page itself. This is fine for smaller projects or in situations where the styles you’re defining will only be used in a single page. There are many times when you will be applying your styles to many pages and it would be a hassle to have to copy and paste your CSS code into each page.

Besides the fact that you will be cluttering up your pages with the same CSS code, you also find yourself having to edit each of these pages if you want to make a style change. Like with JavaScript, you can define/create your CSS styles in a separate file and then link it to the page you want to apply the code to:

<link href=”myFirstStyleSheet.css” mce_href=”myFirstStyleSheet.css” rel=”stylesheet” type=”text/css”>

The above line of code links your external style sheet called ‘myFirstStyleSheet.css’ to the HTML document. You place this code in between the <head> </head> tags in your web page.

HOW TO CREATE A LINKED EXTERNAL STYLE SHEET

To create an external style sheet all you need to do is create a simple text document (on windows you simply right-click and select new -> text document) and then change the file from type .txt to .css.

You can change the file type by just changing the files’ extension. The files’ extension on windows tells the computer what kind of file it is and allows the computer to determine how to handle the file when for example you try to open it.

You probably guessed it; CSS files are just specially formatted text files, and much in the same way HTML pages are. There is nothing special or different in the file itself, rather it is the contents of the file that make an HTML document and a CSS page what they are.

When working with a external CSS document, there are a couple of points to remember:

1. You don’t add these tags in the CSS page itself as you would if you embedded the CSS code in your HTML:

<style type=”text/css”>

</style>

Since the CSS link in your web page says that you are linking to a CSS page, you don’t need to declare (in the external CSS file) that the code in the CSS page is CSS. That is what the above tags do. Instead you would just add your CSS code directly to the page like so:

.myNewStyle {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-weight: bold;
color: #FF0000;
}

.my2ndNewStyle {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-weight: bold;
color: #FF0000;
}

.my3rdNewStyle {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 12pt;
color: #FF0000;
}

In the above example I have created a series CSS classes that can be applied to any HTML tag like so:

<p class=”myNewStyle”>My CSS styled text</p>

or

<h2 class=”my3rdNewStyle”>My CSS styled text</h2>

You will notice that in the above example I applied a CSS style to a <h2> tag. Normally this tag sets the size of the text that it wraps to a size that is preset in the browser (ex: 10 pixels).

When you apply a CSS class to it, the CSS code overrides the default size that you would normally get with an <h2> tag in favor of the size specified in the CSS class. So now you can see that CSS can override default HTML tag behavior!

In the above examples, I have CSS code where I define my CSS classes and then ‘apply’ them to various elements in the page. Another way to apply CSS is to globally redefine an HTML tag to look a certain way:

h1 { font-family: Garamond, “Times New Roman”, serif; font-size: 200%; }

What this CSS code does is set the font style and size of all <h1> tags in one shot. Now you don’t have to apply a CSS class as we did before to any <h1> tags since they are automatically all affected by the CSS style rules.

Here is another example of where I give the whole page bigger margins:

body { margin-left: 15%; margin-right: 15%; }

As you can see, you can redefine any tag and change the way it looks! This can be very powerful:

div {
background: rgb(204,204,255);
padding: 0.5em;
border: 1px solid #000000;
}

The above CSS code sets that any <div></div> tag will now have a background color of ‘rgb(204,204,255)’ and have a padding of 0.5em and a thin 1 pixel border that is solid black.

A few things to explain about the above:

Color in CSS can be expressed in a few ways:

1. In Hex -> for example: #000000 – this is black and this: #FF0000 is red.
2. In rgb -> rgb(204,204,255) is a light purple blue color.
3. With named colors like: ‘red’ or ‘blue’

I typically use hex color since I am familiar with them or I just use named colors. So the last example can be rewritten like so:

div {
background: green;
padding: 0.5em;
border: 1px solid #FF0000;
}

So instead of ‘rgb(204,204,255)’ , I just specified ‘green’.

By using RGB (RGB is the acronym for: ‘Red Green Blue’) and Hex color, you can really get the exact color you want easily when you know your codes. Luckily many programs (like Dreamweaver) provide easy to use color pickers for you so you don’t need to know the values for the code.

In this last example I will show you the ‘super cool’ CSS code that allows you to create link roll-over affects without images:

a:link { color: rgb(0, 0, 153) }
a:visited { color: rgb(153, 0, 153) }
a:hover { color: rgb(0, 96, 255) }
a:active { color: rgb(255, 0, 102) }

The above CSS will cause your links to change color when someone hovers their mouse pointer over it, instant rollovers with no images! One important note with the above code is that it is important that the style declarations be in the right order: “link-visited-hover-active”, otherwise it may break it in some browsers.

CSS is very powerful and allows you to do things that you can’t do with standard HTML. It is supported nicely now in all the modern browsers and is a must learn tool for web designers. The above examples are just a small sample of what you can do with CSS, but it should be more than enough for you to start styling your pages nicely. Like with many technologies CSS has a lot of capability that most people will not need to use often if at all. Don’t get caught in the trap of thinking that if there is some functionality/feature available that you have to use it.

 

JavaScript Object-Oriented Programming Part 2

July 31, 2007
  
In Part 1 of this series, we covered objects, object methods, and object categories. Now, let’s move on.
Arguments

In every function, a private variable — argument — is automatically created, holding an array of the arguments passed to the function. For example:

function testArg(){
 for(i=0;i<arguments.length;i++){
   alert("Argument "+i+" is "+arguments[i]);
 }
}

As demonstrated in the example above, we can access the set of arguments passed when calling a function with the arguments variable that exists in the function’s scope. This example shows that we can access all of the arguments in a function without specifying them as parameters when we define the function. This can be particularly useful when we don’t know exactly how many arguments we’re going to pass.

Therefore, we can use:

testArg("PageResource","SitePoint","JavaScriptCity",
       "WebSite Abstraction");

…to get an alert of some of my favorite Web development sites.

Complex Example

Now that we have a foundation in object-based programming in JavaScript, let’s build an intricate object-based example, a library. We’ll just keep track of some basic information, such as the book titles, authors, pages, and price. To accomplish this, we’re going to have a Person object (that represents each author), a Book object, and a Library object. First, let’s create the Person() object constructor:

function Person(lastName, firstName){
 this.lastName = lastName;
 this.firstName = firstName;
}

And now, let’s create some instances of our Person object:

var DnnyGdmn = new Person("Goodman","Danny");
var DvdFlngn = new Person("Flanagan","David");
var TmMyrs = new Person("Myers","Tom");
var AlxNkmvsky = new Person("Nakhimovsky","Alexander");

Next, let’s create our Book object. Its properties will be:

  • title
  • pages
  • price
  • author(s)

Lastly, we can have multiple authors for the same book, so we need to be able to accept more than one Person object as an author. To do this, we’ll create an array to hold each person that wrote the book.

function Book(title, pages, price){
 this.title = title;
 this.pages = pages;
 this.price = price;
 this.authors = new Array(arguments.length-3);
 for(i=0;i<arguments.length-3;i++){
   this.authors[i] = arguments[i+3];
 }
}

The first part of that code should seem straightforward; however, the last part may not. So, let’s examine it more closely:

this.authors = new Array(arguments.length-3);

This creates an author property for our Book object. The author property is itself an Array object. When we call our Book() constructor, the first three arguments are title, pages, and price, respectively, so those arguments that are specified after these are our authors. Therefore, if we pass five arguments, we know that two of those must be authors. So we can create an Array object with a length of arguments.length-3.

for(i=0;i<arguments.length-3;i++){
 this.authors[i] = arguments[i+3];
}

This code loops through the arguments and assigns them to the Array object. Now, let’s see how we can create instances of this Book object:

 var JavaNut = new Book("Java Foundation Classes in a  
Nutshell", 731, 29.95, DvdFlngn);
 var JSTDR = new Book("Javascript: The Definitive Guide (3rd  
Edition)", 776, 39.95, DvdFlngn);
 var JSBible = new Book("Javascript Bible, 4th Edition",  
1200, 49.99, DnnyGdmn);
 var DHTMLTDR = new Book("Dynamic Html: The Definitive  
Reference", 1073, 44.95, DnnyGdmn);
 var JSObj = new Book("JavaScript Objects", 450, 39.99,  
TmMyrs, AlxNkmvsky);

Note that we’re passing instances of the Person object as the last arguments to create the authors property of the Book object. A key concept in OOP design (as in Relational Database design) is to avoid repetition within data. Therefore, we create one Person object for each distinct author. So, even though David Flanagan may write more than one book, we always refer to the same Person object. Also, if David ever decides to change his first name to “Bebop”, we can easily change it for all records, by simply altering the one Person object that holds this information. In addition, note that instead of passing primitive data types, we could have passed objects. For instance, for the title, we could have passed a String object, and for the page number, we could have passed a Number object. However, here, they wouldn’t serve much use, so we used a primitive data type – this fits our needs just perfectly.

Now, let’s move on to perhaps the most difficult object constructor, the Library() constructor. I’m going to break this one up in to parts:

function Library(){
 this.books = new Array(arguments.length);
 for(i=0;i<arguments.length;i++){  
   this.books[i] = arguments[i];
 }

The first thing you may notice about this function is that it has no parameters. This is because it only accepts Book objects, though we have no idea how many. It creates a property of the Library object, books, which stores an Array of Book objects. Let’s say we wanted to access a book’s first-listed author. We could use:

this.books[bookIndex].authors[0]

We first access the Library’s book property, which is an Array object. Then, we access a specific Book object. From that Book object, we access its authors property, which is an array. Lastly, we access a specific Person object. And from there, we could go on to access that Person object’s firstName or lastName property. Note that bookIndex is the index of the book we want to access.

Now, that’s the only property that our Library object will contain. The rest will be methods:

this.totalPrice = function(){
 var totalCost = 0;
 for(i=0;i<this.books.length;i++){
   totalCost += this.books[i].price;
 }
return totalCost;
}

This method loops through our books property, which is an Array object, takes the price of each Book object and adds it up, and finally returns the value.

this.averagePrice = new Function("return this.totalPrice
()/this.books.length");

This method takes the total price of all of our books and divides it by the number of books we have, to find out the average price of our books. So, once we create a Library object, how do we add more books to it? We’re going to have to create another function:

this.addBook = new Function("book", "this.books.push(book)");

This uses the Array‘s built-in method, push(). The push() method adds the value or object passed as an argument to its Array object, while making sure to change the Array‘s length property. Lastly, we’ll create a method to display the names of the authors in our library. This method is rather long, so I’ll split it up:

this.getAuthors = function(){
 var toSay = "Your favorite authors are:\n";

This creates a method we’ll use to retrieve the list of authors. The toSay variable will hold the string of what this method returns.

for(i=0;i<this.books.length;i++){
 for(j=0; j<this.books[i].authors.length;  
j++){
   var authName =
   this.books[i].authors[j].firstName + " " +
   this.books[i].authors[j].lastName;

This portion of the code loops through all the books, and then loops through all the authors of that book, placing their names in the authName variable.

if(toSay.indexOf(authName)!=-1) continue;        
 toSay+="\n\t"+authName;

If this author is already in the toSay variable, we don’t want to add him again, so we continue to loop through the authors of this book. However, if the author is not yet listed, we can go ahead and add him or her to the toSay variable.

     }
   }
   return toSay;
 }
}

That closes the two for loops we had open, and returns the toSay variable. It also closes out the method we’ve been defining, getAuthors(), as well as closing out the Library() constructor. Now, let’s put all the code together, and create a new Library object:

// define our Person() constructor
function Person(lastName, firstName){
 this.lastName = lastName;
 this.firstName = firstName;
}
// define our Book() constructor
function Book(title, pages, price){
 this.title = title;
 this.pages = pages;
 this.price = price;
 this.authors = new Array(arguments.length-3);
 for(i=0;i<arguments.length-3;i++){
   this.authors[i] = arguments[i+3];
 }
}
//define our Library() constructor
function Library(){
 this.books = new Array(arguments.length);
 for(i=0;i<arguments.length;i++){
   this.books[i] = arguments[i];
 }
 
 this.totalPrice = function(){
   var totalCost = new Number(0);
   for(i=0;i<this.books.length;i++){
     totalCost += this.books[i].price;
   }
 return totalCost;
 }
 
 this.averagePrice = new Function("return  
this.totalPrice()/this.books.length");
 
 this.addBook = new  
Function("book","this.books.push(book)");
 
 this.getAuthors = function(){
   var toSay = "Your favorite authors are:\n";
   for i=0;i<this.books.length;i++){
     for(j=0;j<this.books[i].authors.length;j++){
       var authName =  
       this.books[i].authors[j].firstName + " " +  
       this.books[i].authors[j].lastName;
       if(toSay.indexOf(authName)!=-
1)continue;
       toSay+="\n\t"+authName;
     }
   }
 return toSay;
 }
}
// create some Person objects
DnnyGdmn = new Person("Goodman","Danny");
DvdFlngn = new Person("Flanagan","David");
TmMyrs = new Person("Myers","Tom");
AlxNkmvsky = new Person("Nakhimovsky","Alexander");
// create some Book objects
 JavaNut = new Book("Java Foundation Classes in a  
Nutshell",731,29.95,DvdFlngn);
 JSTDR = new Book("Javascript: The Definitive Guide (3rd
Edition)",776,39.95,DvdFlngn);
 JSBible = new Book("Javascript Bible, 4th  
Edition",1200,49.99,DnnyGdmn);
 DHTMLTDR = new Book("Dynamic Html: The Definitive  
Reference",1073,44.95,DnnyGdmn);
 JSObj = new Book("JavaScript
Objects",450,39.99,TmMyrs,AlxNkmvsky);
// create a Library object
myLib = new Library(JavaNut,JSTDR,JSBible,DHTMLTDR);

Oops, we left out the JavaScript Objects book. We’d better add it:

myLib.addBook(JSObj);

Now, we can get the information, such as how much our library of books cost, the average price of a book, and the names of the authors that have written the various books we own. And that’s it! We’ve completed a complicated OOP example with JavaScript. You might want to go back over any code that you don’t understand, or feel free to post a question in the Client Side Scripting forum at SitePointForums.com.

Prototype

Every object constructor has a special property, prototype. This property allows you to add properties/methods to all objects created from that object constructor. Sound confusing? It’s not. Let’s look at some examples:

function Square(){
}
var squareObj = new Square();
Square.prototype.side = 5;
var squareObj2 = new Square();
alert(squareObj.side); // displays 5
alert(squareObj2.side); // displays 5

What this does is add a side property, with an initial value of 5, to all Square objects, whether they’ve been created, or have yet to be created. The prototype object (it is, in fact, an object) loads before the object constructor does anything. So, this code:

function Square(){
 this.side=5;
}
var squareObj = new Square();
Square.prototype.side = 4;
var squareObj2 = new Square();
alert(squareObj.side); // displays 5
alert(squareObj2.side); // displays 5

returns 5, because everything in the prototype object loads first (before the Square() object constructor even runs), so the properties and methods defined in the constructor will override it. So, with the prototype property, you can’t override any properties or methods defined in an object’s constructor (the function that creates the object). Using the String‘s prototype property, we can add new methods to String objects. Consider this example:

function consonantize(){
 var consonants ="";
 for(i=0;i<this.length;i++){
   var l = this.charAt(i);
   if(l!="a" && l!="A" && l!="e" && l!="E" &&
   l!="i" && l!="I" && l!="o" && l!="O" && l!="u" && l!="U" && l!="
"){
     consonants+=l;
   }
 }
 return consonants;
}

The above function goes through a string and removes all vowels and spaces, returning only consonants. Now, we can use it on any String object, or any String primitive datum:

String.prototype.consonantize = consonantize;
var dg = "Danny Goodman";
var df = new String("David Flanagan");
alert(dg.consonantize());
alert(df.consonantize());

Neat, huh? Note how the new method, just like other String methods, can be used by a String object or by a String primitive data type. Therefore, by using an object constructor’s prototype method, we can add properties and methods to both native objects and user-defined objects.

Constructor

Every instance of an object has a constructor property. It returns the Function object that created that instance of the object. For example:

function myConstructor(){
}
var str = new String("Some String");
var obj = new Object();
var myObj = new myConstructor();
alert(str.constructor); // the native String() constructor
alert(String) // the native String() constructor
alert(obj.constructor); // the native Object() constructor
alert(Object) // the native Object() constructor
alert(myObj.constructor); // the user-defined myConstructor() constructor
alert(myConstructor); // the user-defined myConstructor() constructor

I recommend that you run this example to see what it returns. Notice how each alert returns the Function object that created that instance of the object. Also, notice that JavaScript‘s native objects return “[native code]”. When you retrieve the typeof for a constructor property, you’ll find that it’s the same as the Function object that created it, “function“:

alert(typeof str.constructor); // "function"
alert(typeof String) // "function"
alert(typeof obj.constructor); // "function"
alert(typeof Object) // "function"
alert(typeof myObj.constructor); // "function"
alert(typeof myConstructor); // "function"

All of the above return “function“. Because a constructor property returns a reference to the Function object that created it, the constructor is in fact a constructor method:

function myConstructor(){
 var x = "y";
 this.x = "x";
 return x;
}
var myObj = new myConstructor();
alert(myObj.constructor); // the myConstructor() function object
alert(myObj.constructor()); // "y"

Note that in this example, we return the local variable, x, rather than the object’s property, this.x. So, if every object has a constructor method, and every method is really a Function object, what’s a Function object’s constructor?

alert(myConstructor.constructor);
alert(myObj.constructor.constructor);
alert(myConstructor.constructor.constructor);
alert(myObj.constructor.constructor.constructor);

All of those return the native Function() object constructor. Although that’s trivial, I personally thought it rather interesting- and thought you might too, and it brings me to another point. Constructors are both “types of objects” as well as objects themselves (more specifically, Function objects). Thus, Date is both an object (a Function object) and a “type of object”, from which you can create Date objects, or instances of the Date object. This is true for all native objects and user-defined objects.

The practical value of all this is that, via an object’s constructor method, we can figure out what type of object it is. We can see whether it’s a String object, created from the native String constructor function; whether it’s an Object object, created from the native Object constructor function; or whether it’s one of our user-defined objects, created from a user-defined constructor function.

Besides being a method of an object, constructor() is also a method of a primitive data type. So what does it return? After all, no real constructor function was run to create primitive data types:

var primitiveString1 = "This is a primitive string";
var primitiveString2 = String("This is a primitive string");
var stringObject = new String("This is a String object");
primitiveString1.prop = "This is a property";  
primitiveString2.prop = "This is a property";
stringObject.prop = "This is a property";
alert(primitiveString1.prop) // "undefined"
alert(primitiveString2.prop) // "undefined"
alert(stringObject.prop) // "This is a property"
alert(typeof primitiveString1); // "string"
alert(typeof primitiveString2); // "string"
alert(typeof stringObject) // "object"
alert(primitiveString1.constructor); // "function String(){  
[native code] }"
alert(primitiveString2.constructor); // "function String(){  
[native code] }"
alert(stringObject.constructor); // "function String(){  
[native code] }"

As we can see, both a String primitive data type and a String object have the same constructor(), the native String() constructor. Note that constructor() is the only property/method that a primitive data type holds, so these data types have access to the properties/methods defined in the native object constructor function. For example, a primitive String data type (as well as a String object) has access to the many properties/methods defined in the native String() constructor, including:

  • length
  • anchor()
  • big()
  • bold()
  • charAt()
  • charCodeAt()
  • concat()
  • indexOf()
  • lastIndexOf()
  • sub()
  • substr()
  • substring()

However, a String object may also contain properties/methods that are particular to that object. For example:

var myStringObj = new String("This is a String object");
myStringObj.prop = "This is a property of the object I created";
alert(myStringObj.prop) // "This is a property of the object I created"

As Alex Vincent notes, sometimes you’ll want to turn a primitive data type into an object. For example, let’s say we have a function like this:

function myFunc(param){
 param.property = "I want to add this property";
 alert(param.property); // "undefined"
}

If we decide to use this function and pass it a primitive data type, we can’t also add properties to it, because it’s not an object. And anyway, passing an object is rather cumbersome:

myFunc(new String("This is a String object"));
myFunc(new Number(5));

One way to overcome this, as Alex points out, is as follows:

function myFunc(param){
 param = new param.constructor(param);
 param.property = "I want to add this property";
 alert(param.property); // returns "I want to add this property"
}

That new line looks confusing, but let’s take a step back. Imagine that we wanted to change a primitive Number into a new Number object. We could use:

var myNum = 5;
myNum = new Number(5);

Now let’s take that a step further:

var myNum = 5;
myNum = new myNum.constructor(5);

You must remember that myNum.constructor() is the same as Number(). Then, instead of using 5, we can use myNum, as that, too, is 5:

var myNum = 5;
myNum = new myNum.constructor(myNum);

And the same works for a String primitive data type – as it does for all primitive data types. Therefore, when we pass any primitive data type as an argument to our function, we automatically convert it to an object so that we can add properties/methods to it.

Prototype Revisited

Let’s go back and revisit the Function object’s prototype property. In Java, a popular, well-known feature is to extend a class; however, in JavaScript, most people are unaware that you can do this – but you can! For instance, let’s say we have a Car object. A Corvette and an Ares are two different types of cars, but they are both still cars. In this way, they have similar properties/methods and extend upon the Car object.

Let’s create the three objects we’re going to use – Car, Corvette, and Ares. Then, we’ll discuss the ways for the latter two to inherit the properties/methods of the Car object.

function Car(color){
 this.wheels = 4;
 this.doors = 4;
 this.color = color;
 this.speed = 0;
 this.accelerate = function(){
   this.speed+=20;
 }
 this.brake = function(){
   this.speed-=20;
 }
}
function Corvette(color){
 // all of Car properties/methods
 this.doors = 2;
 this.color = color;
 this.accelerate = function(){
   this.speed+=40;
 }
}
function Ares(color){
 // all of Car properties/methods
 this.doors = 2;
 this.color = color;
 this.accelerate = function(){
   this.speed+=10;
 }
 this.brake = function(){
   this.speed-=10;
 }
}
var myCar = new Car("white");
var myCorvette = new Corvette("black");
var myAres = new Ares("red");

Because a Corvette is an especially fast car, we’ve upped its acceleration speed from a normal car, and because a Dodge Ares is a rickety, old car, we’ve made it so the brakes don’t work as well, and it doesn’t accelerate as fast (no offense to Dodge Ares owners). Now, we could use the Corvette() and Ares() prototype property and add to each the properties/methods from the Car object that we want them to inherit. However, this could be a confusing and tedious task, especially if there are many properties/methods. To overcome this, we need to examine the prototype property again.

The prototype property is an object with no initial properties/methods. When we add properties/methods to this object, we automatically add them to all instances of the object. However, instead of adding properties/methods to the prototype object, we could replace the prototype object with an object that already has the properties/methods we want. For example, instead of using:

Corvette.prototype.wheels = 4;
Corvette.prototype.speed = 0;
Corvette.prototype.brake = function(){
 this.speed-=20;
}

we can more easily use:

Corvette.prototype = new Car();

We can do the same for the Ares object:

Ares.prototype = new Car();

Both the Corvette and Ares objects now have all the Car‘s properties/methods, which can then be overridden by the properties/methods defined in each object constructor. For example, in both the Corvette and Ares objects, the door property is overridden to 2. Altogether, our now code looks like:

function Car(color){
 this.wheels = 4;
 this.doors = 4;
 this.color = color;
 this.speed = 0;
 this.accelerate = function(){
   this.speed+=20;
 }
 this.brake = function(){
   this.speed-=20;
 }
}
function Corvette(color){
 this.doors = 2;
 this.color = color;
 this.accelerate = function(){
   this.speed+=40;
 }
}
Corvette.prototype = new Car();
function Ares(color){
 this.doors = 2;
 this.color = color;
 this.accelerate = function(){
   this.speed+=10;
 }
 this.brake = function(){
   this.speed-=10;
 }
}
Ares.prototype = new Car();
var myCar = new Car("white");
var myCorvette = new Corvette("black");
var myAres = new Ares("red");

Now, from the Corvette and Ares objects, we can retrieve the appropriate properties and run the accelerate() and brake() methods that correspond to those objects. In this way, in JavaScript, object inheritance is not hard to accomplish.

Wrap-up

Through this tutorial, I hope you’ve learned a general understanding of how JavaScript operates. In addition, I hope you’ve gained a basic knowledge of OOP and an understanding of the power of JavaScript as an object-based language. I suggest that you post any questions you might have in the SitePoint Forums; however, if you can’t seem to find an answer to your JavaScript object question, I’d be more than happy to give it a shot if you email me at perwez4u@yahoo.co.in

There have been many people who have helped me write this tutorial. In particular, though, I’d like to thank Alex Vincent, Jason Davis, and Jared for helping me to understand the finer points of JavaScript’s object abilities.

Javascript object oriented programming

July 31, 2007

It may be shocking news, but JavaScript is a very powerful object-based (or prototype-based, whatever you wish to call it) language. Yes, JavaScript is a powerful language, not just something that’s handy for image rollovers and other corny, flashy effects. However, very few people who have used JavaScript realize its capabilities. If you’re one of these people, this blog is aimed at you.

First of all, JavaScript is not a full-blown OOP (Object-Oriented Programming) language, such as Java, but it is an object-based language. So, why should you use objects? Not only do they help you better understand how JavaScript works, but in large scripts, you can create self-contained JavaScript objects, rather than the procedural code you may be using now. This also allows you to reuse code more often.

I hope that this article will turn an intermediate JavaScripter who’s itching to learn objects, into an expert, keen on the exciting object-oriented JavaScript world!

In this tutorial, you’ll learn:

  • JavaScript’s primitive data types
  • What an object is in JavaScript
  • How to create custom objects
  • What a constructor is
  • What an object’s prototype property is
JavaScript’s Primitive Data Types

JavaScript has five primitive data types:

  • Undefined,
  • Null,
  • Boolean,
  • Number, and
  • String. Throughout this tutorial, we’ll use the latter three extensively.

ValueClick Media (click to view image)

(click to view image)

A Boolean is a logical entity that consists of either a true or a false value. An example of one is:

var BooleanValue = true;

A Number is a set of numerical digits that represent a number. Through this tutorial, we’ll only use base-10 numbers. An example:

var NumericalValue = 354;

A String is a set of zero or more characters. An example:

var StringValue = "This is a String";

Typeof

A less-known operator in JavaScript is the typeof operator. It tells you what type of data you’re dealing with. Makes sense, huh? Let’s look at some examples:

var BooleanValue = true;
var NumericalValue = 354;
var StringValue = "This is a String";
alert(typeof BooleanValue) // displays "boolean"
alert(typeof NumericalValue) // displays "number"
alert(typeof StringValue) // displays "string"

An Object

An object is a collection of properties. These properties can either be primitive data types, other objects, or functions (which in this case are called methods, but more on this later). A constructor function (or simply, constructor) is a function used to create an object – this too we’ll discuss in detail later. JavaScript comes with many built-in objects, such as the Array, Image, and Date objects. Many of you are familiar with Image objects from creating those ever-so-cute rollover effects. Well, when you use the code

var Image1 = new Image();
Image1.src = "myDog.gif";

(click to view image)

you have in fact created a new Image object, and assigned a property of your new Image object: the src property. Image1 is a new Image object; in other words, it is an instance of the Image object. Using JavaScript’s dot-structure ( . ), the code above then accesses and sets the src property of your new Image object. Now, let’s learn how to create our own objects.

function myFunc(){
}
var myObject = new myFunc();
alert(typeof myObject);  // displays "object"
We've just created out own object. In fact we've created a myFunc object. myFunc() is a constructor function; it lays out the blueprint from which objects that are created from it will follow (although, in this case, it doesn't lay out much of a blueprint). So, how does JavaScript know to create an instance of the myFunc object, rather than to return its results? Let's compare the example above with the following, more conventional use of a function:

function myFunc(){
 return 5;
}
var myObject = myFunc();
alert(typeof myObject); // displays "number"
In this case, we've assigned 5 to myObject. So, what's the difference between these two scripts? Answer: the new keyword. It tells JavaScript to create an object following the blueprint set forth in the myFunc() constructor function. In fact, when we create an Image object, we do the same thing, except that instead of using our own constructor function, we use one of JavaScript's built-in constructor functions, the Image() constructor function.

So far, we’ve learned how to create a constructor function, and how to create an object from that constructor function. In our example, we’ve created a myFunc() constructor and created an instance of the myFunc object, which we assigned to the variable myObject.

This is all fine and dandy, but what’s the point? Well, just like our Image object, myObject can be assigned properties:

function myFunc(){
}
var myObject = new myFunc();
myObject.StringValue = "This is a String";
alert(myObject.StringValue); // displays "This is a String"
And voila, we've now created a property for our object. However, if we create another instance of the myFunc object (using the myFunc() constructor function), we also have to assign the StringValue property to this new instance. For example:

function myFunc(){
}
var myObject = new myFunc();
myObject.StringValue = "This is a String";
var myObject2 = new myFunc();
alert(myObject2.StringValue); // displays "undefined"
So, how can we create properties that exist for all myFunc objects? Within the myFunc() constructor function, we can do just that. The this keyword inside a constructor function refers to the object that's being created. Example:

function myFunc(){
 this.StringValue = "This is a String";
}
var myObject = new myFunc();
var myObject2 = new myFunc();
alert(myObject2.StringValue); // displays "This is a String"
Now, all myFunc objects will have a StringValue property, assigned with the initial value of "This is a String", but every object can have its own distinctive value for StringValue. In other words, we can change the StringValue property for one myFunc object, without affecting the others:

function myFunc(){
 this.StringValue = "This is a String";
}
var myObject = new myFunc();
myObject.StringValue = "This is myObject's string";
var myObject2 = new myFunc();
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
We can also achieve similar results if we pass arguments to our constructor function:

function myFunc(StringValue){
 this.StringValue = StringValue;
}
var myObject = new myFunc("This is myObject's string");
var myObject2 = new myFunc("This is a String");
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
In the myFunc() constructor, this.StringValue refers to the property being assigned to the newly created object, while StringValue refers to the function's local variable that was passed as an argument. So, now that we've assigned properties to objects, what about methods?

Object Methods

In addition to properties, objects can have methods. An object’s method is a function it can perform. Let’s take a look at this example. For this one, let’s create a Circle object. First, we’re going to have to define our functions, and then make them methods of our Circle object. Let’s define our Circle() constructor and a Circle object or two:

function Circle(radius){
 this.radius = radius;
}
var bigCircle = new Circle(100);
var smallCircle = new Circle(2);
Now, let's define some functions that we might use:

function getArea(){
 return (this.radius*this.radius*3.14);
}
function getCircumference(){
 var diameter = this.radius*2;
 var circumference = diameter*3.14;
 return circumference;
}
Note that if you were going for accuracy, you could use Math.PI instead of 3.14, but we'll use this simplified representation of pi to keep the numbers in our examples nice and round.

These functions are easy, except for one thing: what does this.radius refer to? this always refers to the current object, in this case, the Circle object. So this.radius refers to the radius property of the Circle object. So, how do we attach these functions to our object? It’s not as hard as you might think. Let’s change our Circle() constructor:

function Circle(radius){
 this.radius = radius;
 this.getArea = getArea;
 this.getCircumference = getCircumference;
}

The above assigns the functions getArea and getCircumference to our Circle object, making them methods—functions belonging to our Circle object. We can use methods just like any normal function, but we must first access the object in which the method is encapsulated:

alert(bigCircle.getArea()); // displays 31400
alert(bigCircle.getCircumference()); // displays 618
alert(smallCircle.getArea()); // displays 12.56
alert(smallCircle.getCircumference()); // displays 12.56

Keeping Things Tidy

Let's say we want to keep all our properties and methods in the same place - in the Circle() constructor function. There are many ways to do this. Let's first examine inner functions. An inner function is a function within a function (say that sentence quickly ten times!). Here's what they let us do:

function Circle(radius){
 function getArea(){
   return (this.radius*this.radius*3.14);
 }
 function getCircumference(){
   var diameter = this.radius*2;
   var circumference = diameter*3.14;
   return circumference;
 }
this.radius = radius;
this.getArea = getArea;
this.getCircumference = getCircumference;
}

It's the same code, except that we've moved the functions. Now, inside our two functions, instead of this.radius, we could use just plain old radius because inner functions can access local variables within outer functions. Thus, it would be able to access the radius local variable passed as an argument to the Circle() constructor. Therefore, we could have just as easily used:

function Circle(radius){
 function getArea(){
   return (radius*radius*3.14);
 }
 function getCircumference(){
   var diameter = radius*2;
   var circumference = diameter*3.14;
   return circumference;
 }
 this.radius = radius;
 this.getArea = getArea;
 this.getCircumference = getCircumference;
}

Ok, now let's change the radius of an object and get its area:

bigCircle.radius=50;
alert(bigCircle.getArea()); // displays 31400

(click to view image)

But wait! It returns 31400, rather than the expected 7850. What's wrong? Well, radius refers to the value we passed to the Circle() constructor function, not the value of the object. So when we change the object's radius, the methods getArea() and geCircumference(), keep on using the old radius. So, we really shouldn't use just plain old radius. Instead, we need to use this.radius, as it refers to the current object's radius, whether this property changes after the object is created or not.

Ok, so now we've created a self-contained object constructor - the function that defines an object. Let's look at another way we can create functions inside our Circle() constructor:

function Circle(radius){
 this.radius = radius;
 this.getArea = function(){
   return (this.radius*this.radius*3.14);
 }
 this.getCircumference = function(){
   var diameter = this.radius*2;
   var circumference = diameter*3.14;
   return circumference;
 }
}
var bigCircle = new Circle(100);
var smallCircle = new Circle(2);
alert(bigCircle.getArea()); // displays 31400
alert(smallCircle.getCircumference()); // displays 12.56

Here, we've encountered another way to define a function. We can use:

functionName = function([parameters]){
 // function body
}

In this way, we can create parameters:

functionName = function(parameter1,parameter2,parameter3){
 //function body
}

While functions aren't created this way very often, when we're creating objects, they can be useful shortcuts. These processes also help avoid conflicts with function names. For instance, another object can have a different function with the same name, for example getArea(), without causing a conflict. This is possible because these functions are encapsulated inside an object constructor.

Object Categories

There are three object categories in JavaScript: Native Objects, Host Objects, and User-Defined Objects.

Native objects are those objects supplied by JavaScript. Examples of these are String, Number, Array, Image, Date, Math, etc.

(click to view image)

Host objects are objects that are supplied to JavaScript by the browser environment. Examples of these are window, document, forms, etc.

And, user-defined objects are those that are defined by you, the programmer.

A fundamental concept in JavaScript is that every element that can hold properties and methods is an object, except for the primitive data types. We can use JavaScript's built-in constructor functions (just like the ones we've created) to create objects:

var Image1 = new Image(50,100);
Image1.src = "myDog.gif";

Here we've created a new Image object using the native Image() constructor function with the following properties:

  • width = 50
  • height = 100
  • src = "myDog.gif"

JavaScript also includes an Object() constructor function that can be used to define a new Object object:

var myObj = new Object();

To that "base Object", we can add properties/methods. Every object in JavaScript derives from JavaScript's native Object object.

Let's review a String primitive data type:

var myString = "This is my string";
alert(myString); // displays "This is my string"
alert(typeof myString); // displays "string"

However, we can even make a String an object, by using its constructor function:

var myString = new String("This is my string");
alert(myString); // displays "This is my string"
alert(typeof myString); // displays "object"

Now we've created a String object. We can also do the same with Number and Boolean. But why would we want to? Well, once we've done that, we can add distinctive properties and methods to that object. A primitive data type contains the properties and methods laid out in its object constructor, but it cannot, itself, hold any distinctive properties/methods. For example, a String primitive data type contains the length property as well as the many methods defined in the native String() object constructor, such as substring(). However, a String object contains the properties and methods defined in the String() object constructor as well as any unique values assigned to that particular object. Now, let's create a Number object and add a method to it:

var myNumber = new Number(2);
myNumber.doubleIt = new Function("return this*2");
alert(myNumber.doubleIt()); // displays 4
alert(typeof myNumber); // displays "object"

So, we just created a new Number object, and then we defined a method for it, doubleIt(). Note that typeof myNumber is "object". This is because objects are able to contain unique properties and methods. Primitive data types, such as String, Boolean, Number, Undefined, and Null, cannot, and this is what differentiates the two.

Also, in the example above, we've in fact created another object - a Function object. However, the Function object is different. When we create an object, we first enter the new keyword, then follow it with the object constructor function, and this returns a new instance of that particular object. Then, using the returned value (which we usually assign to a variable), we can add properties and methods to that object. However, because a Function object is also a callable block of code, JavaScript makes the distinction and tells us that it's not only an object (which it is, as we can add properties and methods to it), but is also a callable block of code. So, when we enter:

alert(typeof myNumber.doubleIt) // displays "function"

it displays "function", rather than "object" as you might have expected. The Function() constructor function can take more arguments. The last argument passed to the Function() constructor becomes the body of the function, while the others become parameters:

var myFunc = new Function("parameter1","parameter2",
 "parameter3"," // function body");

Now we can call that function and specify three arguments:

myFunc("argument1","argument2","argument3");

Function Objects

JavaScript's Function object is unususal for a number of reasons. Firstly, it's a callable block of code. And a function is always an object - it always has the ability to hold unique properties and methods. The creation of a function automatically creates a Function object:

function myFuncObj(){}
myFuncObj.someVariable = "x";
alert(myFuncObj.someVariable) // displays "x"

Even without the new keyword, Function() creates an object, capable of containing properties and methods. Note that the Function() constructor is a special case – all other constructors must be called with the new keyword, or they simply return a value, instead of a new object.

Let's look at a String primitive data type vs. a String object:

var pimitiveString1 = "This is a primitive string";
var pimitiveString2 = String("This is a primitive string");
var stringObject = new String("This is a String object");
primitiveString1.prop = "This is a property";
primitiveString2.prop = "This is a property";
stringObject.prop = "This is a property";
alert(primitiveString1.prop) // displays "undefined"
alert(primitiveString2.prop) // displays "undefined"
alert(stringObject.prop) // displays "This is a property"

alert(typeof primitiveString1); // displays "string"
alert(typeof primitiveString2); // displays "string"
alert(typeof stringObject) // displays "object"

Here you can see that, without the new keyword, we don't create and assign an object to a variable, but instead, we assign the returned value (which is a primitive data type, String) to a variable. You can also see that primitiveString1 and primitiveString2 are not objects, as we cannot assign them properties. Note that primitiveString1/primitiveString2 and stringObject return different results when used with the typeof operator. This is even true for Date, Image, Option, and other objects. For example:
var x = Date();
alert(typeof x); // displays "string"

No matter how you create a function (there are numerous ways), you'll automatically create an object:

var myFuncObj = new Function();
var myFuncObj = Function();
var myFuncObj = function(){}
function myFuncObj(){}

Here, we've examined the different ways to create a Function object that's capable of holding a callable block of code, as well as any disctinct properties or methods.

In Summary

Before we move on, let's review some key points:

  • In JavaScript, there are five primitive data types: Undefined, Null, Boolean, Number, and String.
  • In JavaScript, everything is an object, except for the primitive data types.
  • An object is an unordered collection of properties. Properties may represent primitive data types, objects, or Function objects, in which case they are called "methods".
  • There are three main object categories in JavaScript: native objects, host objects, and user-defined objects.
  • There are many built-in, native objects, such as Object, Image, Date, Option, etc. However, we can also create our own user-defined objects, such as the Circle object.
  • An object constructor/object constructor function is a function that's used to define a new object. In this function, we declare the initial properties/methods of the new object, and usually assign them a pre-defined value.
  • To create an instance of an object, we use the keyword "new", followed by an object constructor. We can either use JavaScript's built-in constructors to create a native object, or we can build our own constructors to create a user-defined object.
  • Every object method has a variable - this - which refers to the current instance of that object from which the method is called. Example:
    • myObj.myFunc()
    • yourObj.myFunc()

    In the first example, in myFunc(), the variable this would refer to myObj. However, in the second example, in myFunc(), the variable this would refer to yourObj.

Javascript

July 30, 2007

JavaScript

 

  1. JavaScript was originally developed by Brendan Eich of Netscape in 1995. It was originally called live script.
  2. Javascript can make our website more dynamic. Dynamic websites can react to events and allow user interaction.
  3. JavaScript was designed to add interactivity with HTML pages.
  4. Javascript executes without preliminary compilation so it is an interpreted language.
  5. Object-based scripting language for client and server applications.
  6. A JavaScript consists of lines of executable computer code
  7. Everyone can use JavaScript without purchasing a license

 

Use of JavaScript:

 

  1. JavaScript can be used to detect the visitor’s browser.
  2. JavaScript can be used to validate data
  3. JavaScript can check the computer’s clock and pull the appropriate data based on the clock information.
  4. JavaScript can store information on the visitor’s computer and retrieve it automatically next time the user visits your page.
  5. JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on a button.
  6. JavaScript can randomly display content without the involvement of server programs. It can read and change the content of HTML elements or move them around pages.
  7. JavaScript can read and write HTML elements
  8. JavaScript can be used to create cookies

 

JavaScript Versions:

 

            Browser                                  Year                            JavaScript Version

 

Netscape Navigator 2.0                        1995                            JavaScript 1.0

Microsoft Internet Explorer 3.0 1996                            JavaScript 1.0 (JScript 1.0)

Netscape Navigator 3.0                        1996                            JavaScript 1.1

Netscape Navigator 4.0                        1997                            JavaScript 1.2

Microsoft Internet Explorer 4.0 1997                            JavaScript 1.2 (JScript 3.0)

Netscape Navigator 4.5                        1998                            JavaScript 1.3

Microsoft Internet Explorer 5.0 1999                            JavaScript 1.3 (JScript 5.0)

                                                                                                JavaScript 1.4

Navigator 6.0/Mozilla 0.6x-0.9x                                               JavaScript 1.5

Mozilla Firefox 1.5                                                                   JavaScript 1.6

Mozilla Firefox 2                                                                      JavaScript 1.7

Client-Side JavaScript

When a JavaScript interpreter is embedded in a web browser, the result is client-side JavaScript. This is by far the most common “flavor” of JavaScript; when most people refer to JavaScript, they usually mean client-side JavaScript.

 

Enhancement of JavaScript 1.1 over 1.0

1. JavaScript 1.1 provides much better support for arrays than JavaScript 1.0 does. 

2. JavaScript 1.1 supports something known as a “prototype object” that makes it much easier to define complex data types.

 

 

New Features of JavaScript 1.2

 

  1. Regular expressions
  2. Signed scripts
  3. Labeled statements
  4. Switch statements

 

 

New Features of JavaScript 1.3

 

JavaScript 1.3 introduces new and modified Date methods to support a full-year notation, milliseconds, and Universal Coordinate Time.

 

JavaScript 1.3                        JavaScript 1.2

 

            getFullYear()                            getYear()

            setFullYear()           setYear()

      getMilliseconds()       None

      setMilliseconds()       None

      toUTCString()           getMonth()

 

In JavaScript 1.3, the Function object has been extended with two new methods, call() and apply().

            New Features of JavaScript 1.4-iPlanet Web Server 4.1 (iWS 4.1)  

Exception handling.

You can throw and catch exceptions using the throw and try…catch statements.

New operators in and instanceof.

The in operator returns true if the specified property is in the specified object. The instanceof operator returns true if the specified object is of the specified object type.

Changes to LiveConnect.

Several changes to LiveConnect improve the way Java and JavaScript code communicate:

    1. The methods of java.lang.Object are inherited by JavaArray. In addition, the JavaArrary.toString method now calls the method java.lang.Object.toString.
    2. You can pass a JavaClass object to a Java method which requires an argument of type java.lang.Class instead of creating a wrapper around an instance of java.lang.Class.
    3. You cannot construct an instance of JSException with a detail message.
    4. The three original public constructors for the Java class netscape.javascript.JSException that supported this feature are deprecated.
    5. You cannot use the == operator to compare two instances of JSObject. Use JSObject.equals.

Changes to the eval method.

    1. The top-level eval method cannot be called indirectly. In previous versions, it was recommended that this method not be called indirectly; starting with JavaScript 1.4, calling eval indirectly could result in a runtime error. This change improves performance.
    2. The eval method is no longer available as a method of Object; use the top-level eval function instead.

Changes to the Function object.

    1. You should no longer specify a function name when using the arguments array; the arguments array is a variable and is no longer a property of Function objects. This change improves performance.
    2. Deprecated the Function.arity property. It has been replaced by the Function.length property.

 

New Features of JavaScript 1.5

Runtime errors:

Runtime errors are now reported as exceptions.

Number formatting enhancements:

Number formating has been enhanced to include Number.prototype.toExponential, Number.prototype.toFixed, and Number.prototype.toPrecision methods.

Regular expression enhancements:

  • Greedy quantifiers - +, *, ? and {} – can now be followed by a ? to force them to be non-greedy.
  • Non-capturing parentheses, (?:x) can be used instead of capturing parentheses(x). When non-capturing parentheses are used, matched subexpressions are not available as back-references.
  • Positive and negative lookahead assertions are supported. Both assert a match depending on what follows the string being matched.
  • The m flag has been added to specify that the regular expression should match over multiple lines.

Conditional function declarations:

Functions can now be declared inside an if clause.

Function expressions:

Functions can now be declared inside an expression.

Multiple catch clauses:

Multiple catch clauses in a try...catch statement are supported.

Constants:

Read-only, named constants are supported. This feature is available only in the C implementation of JavaScript.

Getters and Setters:

JavaScript writers can now add getters and setters to their objects. This feature is available only in the C implementation of JavaScript.

 

 

New Features of JavaScript 1.6

 

  1. E4X (ECMAScript for XML)
  2. Several new Array methods:

Item locator methods:

  • indexOf() – returns the index of the given item’s first occurrence.
  • lastIndexOf() – returns the index of the given item’s last occurrence.

The iterative methods:

  • every() – runs a function on every item in the array and returns true if the function returns true for every item.
  • filter() – runs a function on every item in the array and returns an array of all items for which the function returns true.
  • forEach() – runs a function on every item in the array.
  • map() – runs a function on every item in the array and returns the results in an array.
  • some() – runs a function on every item in the array and returns true if the function returns true for any item.
  1. Array and String generics.

 

 

New Features of JavaScript 1.7

 

 

  1. Generators
  2. Iterators
  3. Array comprehensions
  4. let expressions
  5. Destructuring assignment

 

 

 

 

 

 

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

confirm("sometext")

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

alert("sometext")

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.

prompt("sometext","defaultvalue")

while
The while loop is used to execute a block of code as long as some condition is true. If the condition is false from the start the block of code is not executed at al. The while loop tests the condition before it’s executed so sometimes the loop may never be executed if initially the condition is not met. Its syntax is as follows.

while (tested condition is satisfied)
{
block of code
}

Defining Arrays

The Array object is used to store a set of values in a single variable name.

for
The third and last looping construct in C is the for loop. The for loop can execute a block of code for a fixed or given number of times. Its syntax is as follows.

for (initializations;test conditions;increment value)
{
block of code
}

DOM

<!–[if !supportLists]–>1.      <!–[endif]–>Document Object Model

<!–[if !supportLists]–>2.      <!–[endif]–> The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents

<!–[if !supportLists]–>3.      <!–[endif]–>The HTML DOM is platform and language independent. It can be used by any programming language like Java, JavaScript, and VBScript.

Cookie

A message given to a web browser by a web server. The browser stores the message in a text file.  The message is then sent back to the server  each time the browser requests a page from the server.

      A very small text file placed on your hard drive by a Web Page server. It is essentially         your identification card, and cannot be executed as code or deliver viruses. It is uniquely  yours and can only be read by the server that gave it to you.

 

A Cookie’s Purpose is:

To tell the server that you returned to that Web page.

How a Cookie Helps You:

 

It saves you time.

If you personalize pages, or register for products or services, a cookie helps Microsoft remember who you are.

Next time you return, we know to show you the information you requested. Or, when you register for another product or service, all you need to do is type in your e-mail address and a password. We then fill in any questions you’ve already answered. Of course, if you never register or leave personal information with Microsoft, then the server only knows that someone with your cookie has returned to the Web site. You are in charge of deciding whether we know anything about you. But the more you tell us about yourself, the more we can help you find information or products you want.

Remember: you can always edit any personal information you give Microsoft by stopping at the Profile Center.