"fallenrogue" Under Leon's hat.

Wed Dec 16

JavaScript Part 3 - Prototype Based Language

For a few years the alpha geek crowd has been debating (read: justifying their own preferences) what type of Object Oriented Language features are the most developer friendly. I never have the heart to remind these folks that everyone experiences the world differently and some will always understand class based OO and others want something else. Well, one of those “something else” is used in JavaScript: Prototype Based Objects.

Given my known readership and audience I’m going to assume you’re all familiar with a class based language. I’m going to use C# in this example but the comparison should hold up for similar languages like Java.

Let’s take a look at defining a class with with to create objects (a.k.a. instances). My example is a simple model that most folks can relate to… Person!

C#

Now let’s do the same thing in JavaScript…

JavaScript

These examples are nearly identical from the standpoint that they represent the same data. They are 2 ways of saying the same thing, one in class based way and the other in a prototype based way. By assigning the proto attribute on a prototype based language you’re essentially saying this is your new “parent”, thus providing the object the features and functionality.

Now, in the JavaScript version we did not create a constructor for creating those objects but we can do that too if we like…

And finally, remember that our functions are first class citizens and can be used to establish members for an object.

Now, proto is not the idiomatic why of defining this inheritance. Most the time you’ll see the more common “prototype” property. Why did I show the other? Just giving you options. Here’s a slight variation on what we’ve done using the prototype object.

As you can see, this is very close to the version I presented and is more common. It’s nice to know but methods just for your own reference. I personally prefer the latter but that could be habit more than preference.

OK, well, that’s basically it for now from a 500000 foot view. Well talk more about this awesome topic soon!

Comments (View)
blog comments powered by Disqus