Monday, May 27, 2013

Objects, objects everywhere.....

To a fish, water is everywhere and its whole world…….

I have spent my professional career developing software using object oriented development techniques, so when I started using Javascript the first thing I looked for was a way to express my objects. I looked for some kind of template/class syntax to define an object and declare it, but only found functions, variables, object instances and other language constructs. 

I constantly felt like objects were all around me and I just couldn't see them. Then suddenly like a slap to my face I awoke and could see them everywhere. So much so that in a web browser everything that you define is just an attribute of a global object, window

A name is not just a name, "function" is what created the confusion in my mind. I did not grasp that a function is the major expression of object oriented features in Javascript. Once I understood function = object, everything else just fell into place. 

Enough chat, how do we create these objects?

The simplest way is as follows

var myBlog = new Object();
myBlog.title = "Just Nonsense";
myBlog.author = "Da Doodler";

Each property of the object can contain any value, functions or objects.

You can also create objects using the object literal notation

var myBlog = {
    title: "Just Nonsense",
    author: "Da Doodler"
}

and then of course you can do the following as well

var myBlog = function blog(theTitle, theAuthor) {
    this.title = theTitle,
    this.author = theAuthor,
}

So many ways, so many choices, feel the liberation!!!

So just how object oriented is Javascript? Find out in the next episode....


No comments: