Senin, 19 Januari 2009

Javascript

Sejarah
Javascript diperkenalkan pertama kali oleh Netscape pada tahun 1995. Pada awalnya bahasa yang sekarang disebut JavaScript ini dulunya dinamai “LiveScript” yang berfungsi sebagai bahasa sederhana untuk browser Netscape Navigator 2 yang sangat populer pada saat itu. Kemudian sejalan dengan sedang giatnya kerjasama antara Netscape dan Sun (pengembang bahasa pemrograman “Java”) pada masa itu, maka Netscape memberikan nama “JavaScript” kepada bahasa tersebut pada tanggal 4 desember 1995. Pada saat yang bersamaan Microsoft sendiri mencoba untuk mengadaptasikan teknologi ini yang mereka sebut sebagai “Jscript” di browser milik mereka yaitu Internet Explorer 3. JavaScript sendiri merupakan modifikasi dari bahasa pemrograman C++ dengan pola penulisan yang lebih sederhana dari bahasa pemrograman C++.

Pengertian
JavaScript adalah bahasa pemrograman yang khusus untuk halaman web agar halaman web menjadi lebih hidup. Kalau dilihat dari suku katanya terdiri dari dua suku kata, yaitu Java dan Script. Java adalah Bahasa pemrograman berorientasi objek, sedangkan Script adalah serangkaian instruksi program.

Hal-Hal Yang Harus Diperhatikan
Ada beberapa hal yang harus diperhatikan dalam pengelolaan pemrograman JavaScript, diantaranya JavaScript adalah “case sensitive”, yang artinya JavaScript membedakan huruf besar dan huruf kecil, Jika Anda pernah belajar bahasa pemrograman seperti Turbo C atau C++, maka sama seperti bahasa pemrograman tersebut, dimana huruf T tidak sama dengan huruf t. Dalam bahasa pemrograman JavaScript juga, sebagai contoh fungsi perintah var tidak boleh ditulis Var dan juga tidak boleh ditulis VAR (huruf besar semua), yang benar adalah var (huruf kecil semua). Perintah lain adalah new Date tidak boleh ditulis new date (huruf kecil semua), dan banyak yang lainnya.

try/catch/finally lets you deal with exceptions gracefully. It does not catch syntax errors, however (for those, you need to use the onerror event). Normally whenever the browser runs into an exception somewhere in a JavaScript code, it displays an error message to the user while aborting the execution of the remaining code. You can put a lid on this behaviour and handle the error the way you see fit using try/catch/finally. At its simplest you'd just use try/catch to try and run some code, and in the event of any exceptions, suppress them:



try{
undefinedfunction()
}
catch(e){
//catch and just suppress error
}


Assuming undefinedfunction() is undefined, when the browser runs the above, no errors will be shown. The syntax for try/catch/finally is a try clause followed by either a catch or finally clause (at least one or both of them). The catch clause if defined traps any errors that has occurred from try, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:


try{
undefinedfunction()
alert('I guess you do exist')
}
catch(e){
alert('An error has occurred: '+e.message)
}


Click on the above button, and notice how only "An Error has occurred" alert pops up, but not "I guess you do exist". This tells us that when try encounters an error, it immediately skips any remaining code inside it and goes straight to catch. The default error message is obviously suppressed, though you can still retrieve this information by accessing the Error object that gets indirectly passed into catch. We'll look at the Error object in detail on the next page.

There's another clause, finally, that if defined will be executed regardless of whether an error occurs in the try clause proceeding it:


try{
undefinedfunction()
alert('I guess you do exist')
}
catch(e){
alert('An error has occurred: '+e.message)
}
finally{
alert('I am alerted regardless of the outcome above')
}


finally can be useful when you need to "clean up" after some code inside try. While it's true finally will always be executed if defined, certain statements inside try such as continue, break, return, or when an error has occurred and there is no catch clause will all cause finally to be executed immediately thereafter. In the following example, the value "5" is alerted, since control is handed over to finally when i reaches 5 inside try:


try{
for (var i=0; i<10; i++){
if (i==5)
break
x=i
}
}
finally{
alert(i) //alerts 5
}


Nested try/catch/finally statements

As a reminder, try should never be defined just by itself, but always followed by either catch, finally, or both. Within each clause, you can define additional try/catch/finally statements following the same aforementioned rule. Take the instance where an error has occurred within the catch clause- defining an additional try/catch statement inside it takes care of it:


var ajaxrequest=null
if (window.ActiveXObject){ //Test for support for different versions of ActiveXObject in IE
try {
ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP")
} //end inner try
catch (e){
alert("I give up. Your IE doesn't support Ajax!")
} //end inner catch

} //end outer catch
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
ajaxrequest=new XMLHttpRequest()

ajaxrequest.open('GET', 'process.php', true) //do something with request


External JavaScript and PHP

One of the lesser known sides of external JavaScript is the ability to reference a PHP file instead of the familiar .js file. At first such an notion may seem strange, even impossible; after all, who among us isn't familiar with that barrier dividing server side and client side scripts that prohibit the two from interacting? Well, it turns out superficial exchange is allowed. Using external JavaScript, you'll see how PHP and JavaScript can work together in a way you may not have thought possible, and to the great benefit of JavaScript.


The syntax

The syntax to referencing a PHP file using external JavaScript is consistent enough with what we already know:

where "myscript.php" is either an absolute or relative path to a PHP script instead of the usual .js file. You can even pass parameters to the PHP script through the URL string:

Your PHP script can then get to these parameters using the global variable $HTTP_GET_VARS[]. So you're probably wondering at this point: "So what's the catch?" Well, there is no catch really, just a few limitations. Since we are invoking the PHP script indirectly and via JavaScript, the final output of the PHP script needs to be valid JavaScript. Think of it as a dynamic .js file, bounded by the same limitations as a regular .js file. A normal PHP script called inside a PHP page can output raw HTML and modify the source code of the page. The JavaScript invoked version obviously cannot, but don't worry, there's plenty of what it can do.

Here's a basic example of a PHP script- ip.php- being called by external JavaScript to do something that JavaScript alone cannot:


//"ip.php" example- display user IP address on any page
Header("content-type: application/x-javascript");
$serverIP=$_SERVER['REMOTE_ADDR'];
echo "document.write(\"Your IP address is: " . $serverIP . "\")";
?>

And once called by external JavaScript:




Output: Your IP address is: 125.161.224.45 <-- Example IP

In the above, we have a normal PHP script that writes out the IP address of the visitor when referenced using external JavaScript, with two important details:

  • A JavaScript header is sent at the very beginning to inform the page that our PHP script is outputting a JavaScript file.
  • Since the final output of our PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax. So to display the IP address from the perspective of JavaScript, the echo function above includes "document.write()" as part the content to send back to the page.

Notice how I didn't output the JavaScript script tag itself (), as just like inside a regular .js file, this isn't required nor valid.

The ability to reference a PHP script inside your external JavaScript can be very useful! It means your JavaScript now has access to once exclusive information on the server side, whether it's the server time, the visitor's IP address, a list of all the files within a certain directory, or mySQL database information. Furthermore, even regular HTML pages can utilize this information, since all that's required is a JavaScript on these pages that in turn references the desired PHP script on your server or beyond. Want to display the visitor's IP address on a static html page- any html page? The above example already does that.

Ok, time to put our new found discovery to better use- how about a JavaScript slideshow that automatically rotates/displays all images within a directory?



JavaScript and Object Oriented Programming (OOP)


JavaScript is an excellent language to write object oriented web applications. It can support OOP because it supports inheritance through prototyping as well as properties and methods. Many developers cast off JS as a suitable OOP language because they are so used to the class style of C# and Java. Many people don't realize that JavaScript supports inheritance. When you write object-oriented code it instantly gives you power; you can write code that can be re-used and that is encapsulated.

What's so great about objects?

Objects work so well because they act just like real life objects- objects have properties and methods. So if we were talking about a lamp, a property of it may be its height or width, say 12cm. A method of it may be to shine (an action). And when it's shining, its brightness property would be of a greater value than when it wasn't.

JavaScript gives you the ability to make your own objects for your own applications. With your objects you can code in events that fire when you want them to, and the code is encapsulated. It can be initialized any amount of times.


Creating objects using new Object()

There are several ways to create objects in JavaScript, and all of them have their place. The simplest way is to use the new operator, specifically, new Object():

We define a custom object "person," then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties.


Creating objects using Literal Notation

Another inline way of defining an object is via literal notation. Supported in JavaScript1.2 and above, it's a more robust form of creating an object on the fly:

Literal notion can contain arrays or arbitrary JavaScript expressions or values.

While using the new operator or literal notion to create a custom object is both simple and logical, the biggest shortcoming is that the result is NOT reusable- we cannot easily initialize different versions of the created object. For example with the first demonstration above, if the person's name is not "Tim Scarfe", we would need to redefine our entire object just to accommodate this change.



JavaScript Closures 101- they're not magic


This tutorial explains closures so that a regular programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers.

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

This article is intended for programmers with some programming experience in a main-stream language, and who can read the following JavaScript function:

function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
sayAlert();
}