Home
1/10/20152
1/4/2015
12/28/2014
12/14/2014
12/13/2014
12/6/2014
11/30/2014
11/29/2014
11/23/2014
11/22/2014
11/15/2014
11/12/2014
11/8/2014
11/1/2014
10/31/2014

December 13
2014

Objects in Ruby vs JavaScript

Objects are the core of any Object Oriented Programming language, but few openly rely on them more than Ruby. In Ruby everything is an object. Numbers, strings, variables, everything is actually an object at its core, with a set of attributes and methods that define how it interacts with all of the other objects. Since JavaScript is a scripting OOP language, it shares many similarities with Ruby. One strange similarity is in their objects.

JavaScript's objects are actually more like Ruby's hashes. They're a collection of attributes (keys) and values that represent what the object is and how it interacts with other objects. Amongst its values can be functions, which are given variables for keys. These functions can be called within the object, much like Ruby would call a method within an object. The key difference is that JavaScript doesn't technically have Classes.

JavaScript does have prototypes, which on the surface look like Classes, but are much different. In Ruby, classes can inherit properties from their SuperClasses. These inheritances look like family trees. As you work your way down the tree, the objects become more complicated and specialized. Every object can only have one parent, but could have many children. With prototypes, JavaScript is made more flexible. Because there is not instantiating of objects, only copying of prototypes, one object could actually consist of the attributes of several prototypes. In a post that I read on StackExchange, it was demonstrated by using the example of an RPG monster called a Steel Golem. This creature would share attributes with other "steel" objects as well as with other "golem" creatures, and it would have characteristics of a "unintelligent monster" also. If this creature was created with classes, it would have a Golem SuperClass, which may have inherited characteristics from the Unintelligent Monster Class, but in order to give it the "steel" attributes that it would have in common with objects like steel swords it would have to include all of that code for each "steel" object. This could become very inefficient.

After reading that, I couldn't imagine why every language wouldn't use multiple inheritance or prototyping, and then I read further. Because the attributes are coming from multiple sources, there can be performance issues because everything has to be looked up separately. If your objects become very complicated it can slow your system down. Also, the programmer needs to do much more testing to ensure all of the objects behave exactly the way they're intended.

In the end, I've come to the realization, again, that the reason for many languages is because they serve many purposes.