Learning Javascript – Part I

Many developers hate Javascript. Nevertheless, they are asked every day to “add a bit of AJAX on the website”.

This post is dedicated to these developers.

Javascript is a rich language, it is object oriented and easy to learn.

The basics
The Mozilla Developer Connection is the best documentation source for Javascript. To learn the syntax and the basic data types, read A re-introduction to Javascript.

Objects
In Javascript, an object is basically a hash. The simplest way to create an object is:

var o = {};
o.name = "hello";
o.setName = function(name) {
  this.name = name;
}

In this example, o is an object, its name property is set to hello, and its setName property is a function.

Classes and inheritance.
Javascript handles the notion of class in an unusual way:

  • a Class is an object of type Function
  • this object has a magic member called prototype
  • when invoked with the new operator, a new empty object is created and the prototype is copied inside.

Example:

var MyClass = function() {
  //contructor
  this.name = "default name";
};
MyClass.prototype = {
  //prototype
  setName: function(name) {
    this.name = name;
  }
};

var o = new MyClass();
alert(o.name); // "default name"
o.setName("new name");
alert(o.name); // "new name"

There are multiple ways to write classes. For a full overview, read the excellent Classical inheritance in Javascript.

Access control
In Javascript, everything is public. The best way to preserve the notion of privacy is through convention. For instance, at Exalead we prefix private members with an underscore.

Everything Dynamic
In Javascript, everything can be changed at all times. Even methods. This is particularly useful when coding event based User Interfaces:

o.onReceiveSomeEvent = function() {
// do something
};

It is even possible to enrich basic data types with your own methods by adding methods to their prototype.

Example:

String.prototype.blank = function() {
  return /^s*$/.test(this);
}
"hello".blank(); // false
"     ".blank(); // true

The DOM – Document Object Model

Javascript runs in the browser in an HTML page. A representation of that page – the DOM – is available to Javascript through the global window object. Of course, it would be too easy if the DOM were identical between browsers. How then, do people write cross browser code? There are 2 approaches at least:

Approach #1:

if (navigator.appName == "Microsoft Internet Explorer"
    && navigator.appVersion >= "4.0") {
  element.attachEvent("onclick", function() {alert("click")});
}

if (navigator.appName != "Microsoft Internet Explorer"
    && navigator.appName != "Netscape") {
  element.addEventListener("click", function() {alert("click")});
}

This is the most trivial approach and the least elegant and scalable. It makes sharing code a nightmare and will inevitably make you hate Javascript. Don’t use it, ever.

Approach #2:

if (element.attachEvent) {
  element.attachEvent("onclick", function() {alert("click")});
}
if (element.addEventListener) {
  element.addEventListener("click", function() {alert("click")});
}

This is a lot better. This approach uses one of javascript’s strengths: testing the existence of a function. It provides maximal compatibility with minimum browser knowledge.

That’s all for today folks! In my next post, we’ll dissect the Prototype Javascript Framework.

Damucho, for the WebDev team

  • Are you sure about this? I can use this for a studi.

  • Very good article I enjoy your blog keep up the amazing posts

  • rajeah

    plz send javascript ebook(tamil)

  • Skan

    Ceci dit, Javascript n’est pas fait pour faire de l’objet. On parle bien de “pseudo-classes”. Et pour certaines fonctions récursives j’ai vu des navigateurs à la ramasse (18 itérations maxi contre plus de 1.000 à l’aise).

    En tout cas, content que Monsieur Propre remette au goût du jour 🙂

    Et quid du SVG? ^^
    Certains navigateurs commencent à bien le gérer nativement 😉