JavaScript – A Different Beast, Part-6: Objects without Classes

Previous topic in this series: Closures

This is the sixth part of my tutorial on JavaScript. Focus of this series is to introduce developers who are comfortable with other programming languages like Java or C to the idiosyncrasies of JavaScript. Basic JavaScript knowledge is assumed, but is not necessary as the code samples are simple and self-explanatory. If you are new to JavaScript, I would suggest going through the previous topics in order.

Topics:

  1. A different beast
  2. Types and Type Conversion
  3. Functions
  4. Scopes and Scope Chain
  5. Closures
  6. Objects without Classes (You are here)
  7. Inheritance without Classes
  8. Arrays, Maps and the for..each loop
  9. Literals and JSON
  10. Dynamic Programming, Exceptions and Module Pattern

Objects

JavaScript is object-oriented in its own sweet way. It sure has objects that encapsulate data and behavior, but decided to do without even the idea of classes! Let me repeat the previous statement to make sure you read it right – JavaScript does NOT have classes, but have objects. Class-less OOP is an extremely rare concept used in programming languages.

Objects in JavaScript are collections of properties that are containers to hold other objects, primitives or functions. A function associated to an object via a property is called a method. For example, Mickey is an object with properties name, age and nibble, where name is associated to a string value of ‘Mickey Mouse’, age is associated to a numeric value of 83 (yes, its true. See Steamboat Willie, 1928) and nibble is associated to a function that does a pretty decent nibbling. The property nibble is therefore termed a method of the object Mickey.

Creation and Destruction of objects

True to the JavaScript style, there are three alternate syntaxes for creating an object – using object literals, using a constructor function and by using the default object constructor function. Following code shows all the three styles.

//Code - 1 - Object Creation
//a) literal approach
var obj1 = {};
console.log(typeof(obj1));
console.log(obj1 instanceof Object);

//b) using new operator with object constructor
var obj2 = new Object();
console.log(typeof(obj2));
console.log(obj2 instanceof Object);

//c) using custom constructor functions:
function car() {}
function jeep() {}
var mycar = new car();
var myjeep = new jeep();
var yourcar = new car(); //create as many as you want!
console.log(typeof(mycar), typeof(myjeep));
console.log(mycar instanceof car,mycar instanceof jeep );
console.log(myjeep instanceof car,myjeep instanceof jeep );

Note: The second approach is actually the same as the third, where the Object constructor is being used instead of a user defined constructor function.

To delete an object, there is only one way (phew!) – using the delete operator. See code below.

//deleting objects
console.log(car);
delete car; //preferred notation
try {
    console.log(car);
} catch(e) {
 console.log("Oops!  " + e);
}

//another syntax for delete operator
console.log(jeep);
delete(jeep);
try {
    console.log(jeep);
} catch(e) {
 console.log("Oops!  " + e);
}

Properties and Methods

Following code samples shows how member variables and methods can be defined for an object. The first code sample uses the literal approach, whereas the second one uses the constructor approach.

//Code - 2 - Object members using literal notation
var mycar = {
    name : 'ferrari',
    color: 'red',
    run : function() { console.log('vroooooom'); }
};

console.log(mycar.name); //ferrari
console.log(mycar.color); //red

mycar.run(); //vrooooom

Now, using the Object constructor:

//Code-3 - Object members using Object constructor
var myjeep = new Object();
myjeep.name = 'willys'; //dynamically adds a property
myjeep['color'] = 'brown'; //another syntax
myjeep.run = function(){ //dynamically adds a function
    console.log('klikkety klikkety');
}

myjeep['stop'] = function() { //alternate syntax
    console.log("i can't"); //note the quotes
}

console.log(myjeep.name); //willys
console.log(myjeep.color); //brown
myjeep.run(); // klikkety klikkety
myjeep.stop(); // i can't

Note: Have you noticed that members can be added dynamically to an object in JavaScript? Also note how similar line-4 is to an associate array available as Map or Dictionary in many programming languages.In fact, objects are used as associative arrays by JavaScript programmers.

Advertisements

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera (www.flickr.com/photos/rahulmohan/) or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on May 21, 2011, in JavaScript, Tutorial and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: