JavaScript objects and Prototype

I am huge devotee of JavaScript. Isn’t it wonderful, a cheap and dainty piece of code that supports the server side code. Even though that’s how it all started, it has grown much. Since the entire industry began moving towards web based apps, so many JavaScript libraries began sprouting like mushrooms. This is a good enough list.

The beauty about JavaScript is that every single thing you see in JavaScript is an object. Isn’t is beautiful, a variable,string,number or even a method is an object. So, whenever you say ‘Object’, what comes to your mind is ‘properties’ and ‘methods’. An example speaks louder than 20 lines, so here goes..

As i just said, everything is an object, even a String variable.

1

I assume what you see above is self explanatory and pretty naive. The entire list of methods and variable for a String object can be found here.

Now, with the basics out of the way, let’s get to some interesting stuff.

Speaking of objects, all the objects in JavaScript are descended from the object Object. Let’s see how to create custom objects in JavaScript.

Yes, JavaScript certainly does have the new operator

1

So we created a variable person ( i repeat, everything is an object) which hails from the object Object. I am setting properties to it. The method which reads the properties are added to it. Finally the method can be invoked just like any normal method.

Well, this is just one way of creating a JavaScript object. There is another way which uses constructors.

1

I would really suggest using the constructor. In the modern world of numerous frameworks and libraries, the more robust and clean the code, the better.

Having said all that, there is an alternate way for the lazy folks.

1

Let’s move on to the JavaScript prototype object.

Take any object in JavaScript and you’ll see it has a property by the name of prototype. This makes it an ubiquitous entity in JavaScript.

All objects inherit methods and properties from prototype. Looking from a developer point of view, prototype can be used to assign a ‘base-class’ object like behavior for JavaScript objects.

1

In the case above, both a musician and a writer can greet themselves. This is done using the greet method. The method is added to the prototype of both the objects.

The above program would alert the following lines,

Greeting and Salutations from Fyodor

This is the time when Fyodor writes

Greeting and Salutations from Bob

This is the time when Bob sings