{"id":259,"date":"2006-08-05T21:01:50","date_gmt":"2006-08-05T21:01:50","guid":{"rendered":"http:\/\/www.bartbusschots.ie\/blog\/?p=259"},"modified":"2014-08-04T14:52:38","modified_gmt":"2014-08-04T14:52:38","slug":"javascript-much-more-than-javas-mini-me","status":"publish","type":"post","link":"https:\/\/www.bartbusschots.ie\/s\/2006\/08\/05\/javascript-much-more-than-javas-mini-me\/","title":{"rendered":"JavaScript &#8211; Much more than Java&#8217;s Mini-Me"},"content":{"rendered":"<p>Something that has annoyed me for a long time is that JavaScript is looked on by many people as just being a stripped down version of Java. You take Java, you take out most of the features and you get JS. This is completely wrong. The two are two completely different languages which follow different paradigms. One is Hard Typed and Object Oriented, the Other is Loosely Typed and Object Based. To give you an idea of just how different the languages are I would say that Java is to JavaScript like C\/C++ is to Perl. I.e. they are completely different languages in just about every respect but their syntax is superficially similar.<\/p>\n<p>Far from being a stripped down version of Java, JS is in many ways a more powerful language and is certainly more feature-rich. And I\u00e2\u20ac\u2122m not talking about little conveniences that make programming a little easier but major features that make some things all but impossible to do with Java but which JS does simply and naturally. In this article I\u00e2\u20ac\u2122m going to look at some of these features. While I was writing this article, I came up with many less dramatic advantages which JS has over Java, which <em>just<\/em> make things easier with JS. Initially I had also included those in this article but they made it too long for the modern attention span. Instead, I\u00e2\u20ac\u2122m compiling them into a separate article with the working title <em>Hidden JS<\/em> which I hope to publish within the next week or so. The inspiration for this article was a post by <a href=\"http:\/\/www.joelonsoftware.com\/AboutMe.html\" target=\"_blank\" title=\"About Joel Spolsky\">Joel Spolsky<\/a> entitled <em><a href=\"http:\/\/joelonsoftware.com\/items\/2006\/08\/01.html\" title=\"Can your programming language do this?\" target=\"_blank\">Can your programming language do this?<\/a><\/em> which details one of the advantages JS has over Java.<\/p>\n<p><!--more--><\/p>\n<h3>Functions as Variables<\/h3>\n<p>This is the feature Joel discussed in great detail so go read <a href=\"http:\/\/joelonsoftware.com\/items\/2006\/08\/01.html\" title=\"Can your programming language do this?\" target=\"_blank\">his article<\/a>, he explains it perfectly so I&#8217;m not going to waste my time doing it again (and probably less well!).<\/p>\n<h3>Multiple Inheritance<\/h3>\n<p>Before I get  into the guts of this one it&#8217;s probably a good idea to point out that JS does all the regular OO stuff. It lets you create objects to encapsulate data and functions, and does inheritance and polymorphism. Yes, it&#8217;s true that it does it in an odd way but it does it all none the less (and no less oddly than Perl). In fact, it does it in multiple ways and the different ways have different advantages and disadvantages.<\/p>\n<p>The way I do OO in JS could best be described as creating classes by writing one function that acts as their constructor. Everything is created within this one function, data structures, functions, and, occasionally, even inner classes. To illuminate this lets have a look at a very simple example, a class to represent a lamp:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/create the class\r\nfunction Lamp(initialState){\r\n  this.isOn = initialState;\r\n\r\n  this.turnOn = function(){\r\n    this.isOn = true;\r\n  };\r\n\r\n  this.turnOff = function(){\r\n    this.isOn = false;\r\n  };\r\n\r\n  this.isOn = function(){\r\n    return this.isOn;\r\n  };\r\n}\r\n\r\n\/\/use the class\r\nvar myLamp = new Lamp(true);\r\nwindow.alert(myLamp.isOn());\r\nmyLamp.turnOff();\r\nwindow.alert(myLamp.isOn());\r\n<\/pre>\n<p>The above code shows how to create a class with one property, <code>isOn<\/code>, and three functions. What happens is that when you create an object with <code>new<\/code> a new blank object gets passed to the function after the word new and that function builds up the object by adding properties and functions to it. Given this it is not hard to imagine how one might implement inheritance, call another function on the object you&#8217;re instantiating from within your &#8216;constructor&#8217; function. Somewhat annoyingly you do this in two steps, first you map a pointer to the other constructor as some property of your new object, then you call it on yourself. I think an example may make things a little clearer so below is the code for making a coloured lamp by extending our lamp class from above:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/create a coloured lamp class\r\nfunction ColouredLamp(initState, initColour){\r\n  \/\/first inherit from Lamp\r\n  this.inheritFrom = Lamp;\r\n  this.inheritFrom(initState);\r\n\r\n  \/\/then create any extra attributes needed\r\n  this.colour = initColour;\r\n\r\n  \/\/then create any extra functions needed\r\n  this.getColour = function(){\r\n    return this.colour;\r\n  };\r\n  this.setColour = function(c){\r\n    this.colour = c;\r\n  };\r\n}\r\n<\/pre>\n<p>Now the thing to note is that there is nothing special about the name I chose for the label for the constructor function we are grabbing from outside (<code>inheritFrom<\/code>). The line that does the inheriting is really no different to calling any function the object contains on itself. Hence, there is no reason you can&#8217;t inherit from more constructors. You can, in fact, inherit from as many as you like.<\/p>\n<p>Let us now imagine that we have created a simple class to represent a paper weight with the properties; weight, and shape. Then, let us imagine that we were mad inventors and we had just invented a combined paperweight and lamp and called it a <em>Paper-Ilumin-Weight<\/em> and that we wanted a JS object to represent it. We could start from scratch and implement a class with the properties colour, state, weight, and shape. But wait, we already have classes for doing both these things complete with all the functions we need for manipulating them. Hence we can just re-use both classes to create our <code>PaperIluminWeight<\/code> class like so:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\/\/create our PaperIluminWeight class\r\nfunction PaperIluminWeight(initColour, initShape, initWeight){\r\n  \/\/inherit from ColouredLamp\r\n  this.inheritFrom = ColouredLamp;\r\n  this.inheritFrom(false, initColour);\r\n\r\n  \/\/inherit from PaperWeight\r\n  this.alsoInheritFrom = PaperWeight;\r\n  this.alsoInheritFrom(initShape, initWeight);\r\n}\r\n<\/pre>\n<p>Now lets have a look at the inheritance tree for the <code>PaperIluminWeight<\/code> class.<\/p>\n<p style=\"text-align:center\"><img decoding=\"async\" id=\"image260\" src=\"http:\/\/www.bartbusschots.ie\/blog\/wp-content\/uploads\/2006\/08\/jsblogpostfigure1.png\" alt=\"Figure 1 - The Inheritance Tree for the class PaperIluminWeight\" \/><\/p>\n<p>Can you do this with Java? In a word, no, because Java does not allow multiple inheritance. You can achieve some of this functionality with interfaces but not a lot. In Java you would have to choose one of the two parent classes to inherit from and then re-create the functionality for the other. Because <code>ColouredLamp<\/code> is more complex (having already inherited from <code>Lamp<\/code>) lets choose that class to inherit from. If we then want to be able to interact with a <code>PaperIluminWeight<\/code> object as a Lamp or a Coloured Lamp it will work fine but we won&#8217;t be able to interact with it as a  PaperWeight. We can make a fudge and re-name our class <code>PaperWeight<\/code> to <code>PaperWeightImplementation<\/code> and create an interface called <code>PaperWeight<\/code> that defines the functions that all Paper Weights should have and then have both <code>PaperWeightImplementation<\/code> and <code>PaperIluminWeight<\/code> implement that interface but that only gets us half way there. We can now use <code>PaperIluminWeight<\/code> objects as Paper Weights within our code but, and this is a hugely important but, we still have to re-implement all the functionality in the <code>PaperWeightImplementation<\/code> class in <code>PaperIluminWeight<\/code> class. I.e. copy and paste the whole lot in. Now, you don&#8217;t need to be a software engineering guru to see that that is an exceptionally bad thing.<\/p>\n<p>Just as the ability to pass functions as variables results in more code re-use and less code replication, so multiple inheritance in JS does the same. JS lets us re-use code in a situation where Java would have us slavishly re-type the same code again with all the software engineering problems that that brings.<\/p>\n<h3>Dynamically Build and Execute Code<\/h3>\n<p>Most scripting languages will allow you to build up a string programmaticaly and then execute it as code and grab the result. This is generally done with a method called <code>eval<\/code> which is exactly how JS does it.<\/p>\n<p>Java does not support this. There is no <code>eval<\/code> method in Java. If you REALLY need to create Java code on the fly and execute it you can do it in a number of <a href=\"http:\/\/mindprod.com\/jgloss\/eval.html\" title=\"eval: Java Glossary\" target=\"_blank\">really convoluted ways<\/a> but for all intents and purposes Java does not support dynamic code generation and execution.<\/p>\n<p>You might wonder why you might want to do that though. So far I have not used it often but I have had to use it. Sometimes I use it for form validation when the form to validate could have a variable number of elements with the same name pattern but this is not a great example because you can also achieve this functionality with DOM objects like <code>document.forms<\/code>. A better example would be a simple calculator widget where you let users build up a string in a disabled text box by clicking buttons on your onscreen calculator and then simply get the answer by putting the value property of that textbox through <code>eval<\/code>.<\/p>\n<h3>One Function, as many or as Few Arguments as You Like<\/h3>\n<p>In JS you can pass as many arguments to a function as you like and that function can then decide what to do with those arguments on the fly. You might wonder what I&#8217;m on about so let me give you an example. You have to write a function that takes any number of integers and adds them together. Before we do this in JS lets do it in Java:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic static int sum(int&#x5B;] nums){\r\n  int ans = 0;\r\n  for(int i=0;i&lt;nums.length;i++){\r\n    ans += nums&amp;#91;i&amp;#93;;\r\n  }\r\n  return ans;\r\n}\r\n&amp;#91;\/java&amp;#93;\r\n\r\n&lt;p&gt;What you should note is that in Java there is no way to make a function take &#039;any number&#039; of arguments so you have to fudge it. In the above code I fudge it by using a single array argument rather than &#039;any number of arguments&#039;. We could also have used some other list structure as the single argument, e.g. a &lt;code&gt;java.util.LinkedList&lt;\/code&gt; or a &lt;code&gt;java.util.Vector&lt;\/code&gt;. What wrapper we decide to use is irrelevant, the point is that we have to somehow wrap our variable length list of arguments into a single argument to keep Java happy.&lt;\/p&gt;\r\n\r\n&lt;p&gt;Now lets have a look at the right way to implement this in JS:&lt;\/p&gt;\r\n\r\n&#x5B;js]\r\nfunction sum(){\r\n  var ans = 0;\r\n  for(var i=0;i&lt;arguments.length;i++){\r\n    ans += arguments&amp;#91;i&amp;#93;;\r\n  }\r\n  return ans;\r\n}\r\n&amp;#91;\/js&amp;#93;\r\n\r\n&lt;p&gt;The code looks quite similar except for one thing: we have not named any of the arguments for the function, instead we are using an array called &lt;code&gt;arguments&lt;\/code&gt;. JS, like Perl, stores it&#039;s arguments in an array but lets you name some or all of them for convenience if you want. (unlike Perl JS does let you pass an array literal as a single argument.)&lt;\/p&gt;\r\n\r\n&lt;p&gt;You would be right in saying that there is very little difference between the JS version and the Java version when it comes to writing the function. There is a line-for-line equivalence between the functions. Where the difference becomes obvious is when you go to use your functions as illustrated below.&lt;\/p&gt;\r\n\r\n&lt;p&gt;Java first:&lt;\/p&gt;\r\n\r\n&#x5B;java]\r\nint&#x5B;] numbers1 = {1, 2, 3, 4};\r\nint ans1 = sum(numbers1);\r\nint numbers2&#x5B;] = {5, 6, 7, 8};\r\nint ans2 = sum(numbers2);\r\n<\/pre>\n<p>Now the JS:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar ans1 = sum(1, 2, 3, 4);\r\nvar ans2 = sum(5, 6, 7, 8);\r\n<\/pre>\n<p>You&#8217;ll notice that the JS code is much simpler. There is only one step involved, call the function and pass it what you want. The Java code on the other hand needs to prepare the array each time before sending it. Things get even worse if you want to do this kind of thing with Objects rather than literals. Have a look at the nasty Java code below:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nInteger numbers1 = new Integer&#x5B;4];\r\nnumbers1&#x5B;0] = new Integer(1);\r\nnumbers1&#x5B;1] = new Integer(2);\r\nnumbers1&#x5B;2] = new Integer(3);\r\nnumbers1&#x5B;3] = new Integer(4);\r\nInteger sum1 = sum(numbers1);\r\nInteger numbers2 = new Integer&#x5B;4];\r\nnumbers2&#x5B;0] = new Integer(5);\r\nnumbers2&#x5B;1] = new Integer(6);\r\nnumbers2&#x5B;2] = new Integer(7);\r\nnumbers2&#x5B;3] = new Integer(8);\r\nInteger ans2 = sum(numbers2);\r\n<\/pre>\n<p>Now the power of this feature of the JS language should be obvious.<\/p>\n<p>More perceptive readers have, at this stage, probably realised that this means that JS does not do function overloading and you would be right. In each scope\/namespace there is only one function with a particular name. If you create a second function with the same name but a different argument list it will replace the first one, ignore the second or throw an error depending on your implementation of JS. You are now probably asking yourself, is this a problem? The answer is no it isn&#8217;t. You do all the work within one function and if you need to do different things depending on what arguments you got you have a look at what&#8217;s in the <code>arguments<\/code> array and take appropriate action. In fact, function overloading is nothing more than a kludge to allow strongly typed languages like Java to approximate variable length argument lists. In general when two functions overload each other they do the same thing but with different data and you just do some converting\/default setting and then pass the data on to the overloaded function that does the actual work. In JS you just write one function that does the work regardless of how you called it. Anything you can do with multiple overloaded functions you can do with one single function in JS and TBH that makes a lot more sense to me, less hoop-jumping and all that.<\/p>\n<h3>Edit Classes on the Fly<\/h3>\n<p>Although it is easy, in Java, to take the functionality from any System object (like <code>java.lang.String<\/code>) and add it to an object of your own (you just extend the class), it is not possible to add functionality <strong>to<\/strong> the System classes. You can&#8217;t, for example, decide that there should be a function in java.lang.Integer to return an Integer which is made up of the digits of the original Integer reversed and add it in to the class (no idea why you&#8217;d want to mind!). No prizes for guessing but, in JS you can. You can take any of the classes of object that come with JS and add your own functionality to them.<\/p>\n<p>The reason you can do this is because of the <code>prototype<\/code> variable that is associated with each object class. When a function is called on an object there are two places that JS looks to find the function to invoke. First it looks to see if the object has a variable of type <code>function<\/code> with the right name, failing that it looks in the <code>prototype<\/code> variable for the class that the object belongs to to see if there is a mapping there. We have already seen the former when creating classes in the second section of this article. In the code examples in that section we created the properties and the functions for an object all within the &#8216;constructor&#8217;, adding functions by setting properties of the class equal to function literals. You don&#8217;t have to do it that way. You can add the functions in separately at any stage using the <code>prototype<\/code> variable but this makes things more difficult for inheriting because prototyped functions cannot be inherited simply by calling a constructor function, they have to be explicitly copied to the inheriting class&#8217; <code>prototype<\/code> variable. This is why I don&#8217;t use <code>prototype<\/code> when creating classes.<\/p>\n<p>Lets now re-visit our <code>sum<\/code> function form the previous section. Rather than having the function as a standalone function that you then have to pass an array to, it would be much nicer to add the summing functionality straight into JS&#8217;s <code>Array<\/code> class. Below is the code to do just that:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nArray.prototype.sum = function(){\r\n  var ans = 0;\r\n  for(var i=0;i&lt;this.length;i++){\r\n    ans += this&amp;#91;i&amp;#93;;\r\n  }\r\n  return ans;\r\n}\r\n&amp;#91;\/js&amp;#93;\r\n\r\n&lt;p&gt;By inserting the code into the Array class this functionality is now automatically added to all arrays so you can now do things like:&lt;\/p&gt;\r\n\r\n&#x5B;js]\r\nvar myArrayOfInts = &#x5B;1, 2, 3, 4];\r\nwindow.alert(myArrayOfInts.sum());\r\n\r\n\/\/because JS is loosly typed even the following will work \r\n\/\/(printing out the Array contents concatonated together)\r\nvar mixedArray = &#x5B;&quot;here&quot;, &quot; &quot;, &quot;are&quot;, &quot; &quot;, &quot;some&quot;, &quot; &quot;, &quot; numbers:&quot;, &quot; &quot;, 1, 2, 3, 4];\r\nwindow.alert(mixedArray.sum());\r\n<\/pre>\n<p>If you&#8217;re already impressed, you&#8217;re about to become even more impressed. The more observant among you will have noticed that if you add functions to an object within it&#8217;s constructor each object has it&#8217;s own copy of the function. This has a downside, it takes up more RAM than the prototyping method, but it makes inheritance easier to implement and it also adds another very interesting ability to the language. In JS it is possible to have two objects of the same type with different implementations of the same function. Take a moment to let that sink in. Without having to create a new class you can make different instances of the same class have different implementations of functions. You just can&#8217;t do that in Java. You&#8217;d have to have a base class with the default implementation of the function in a parent class (or an abstract function if there is no default) and then a separate subclass overriding the function for each different implementation. If you have a couple of functions that that need a couple of implementations things get very out of hand very very quickly.<\/p>\n<p>That&#8217;s great but why on Earth would you want to do that? Well let me give you an example from my everyday life. You want to write a nice object to encapsulate a generic AJAX request because your site uses a lot of AJAX and you&#8217;re tired of typing the same code again and again and would like everything to do with a request encapsulated in an object. You start coding this up and it all goes well till you get to your function for handling state changes in the HTTP Request object in which you have to actually DO something with the response you got from the server. Thing is you want to do something different for each <strong>instance<\/strong> of your class. In Java this is not possible so you would have to write a base class which implements all the functionality for talking to the server and then make your function to actually do something with the response (lets call it <code>process<\/code>) abstract. For each different thing you want to do with AJAX you would then have to create a new subclass of your base class and implement <code>process<\/code>. That is a lot of work for no good reason. In JS you can just create an instance of your AJAX object, plug in a <code>process<\/code> function of your choice using a function literal and then use your object.<\/p>\n<p>In fact, my partner wrote a little JS class to encapsulate AJAX in JS in this way which will be released as GPL soon. This object gets used something like this:<\/p>\n<p>[JS]<br \/>\nvar req1 = new AjaxReq(&#8220;POST&#8221;, &#8220;http:\/\/somewhere.ie\/something.do&#8221;, &#8220;var1=val1&#038;var2=val2&#8221;);<br \/>\nreq1.process = function(req){<br \/>\n  document.getElementById(&#8216;myDynamicDiv&#8217;).innerHTML = req.responseText();<br \/>\n}<br \/>\nreq1.send();<\/p>\n<p>var req2 = new AjaxReq(&#8220;POST&#8221;, &#8220;http:\/\/somewhere.ie\/something.do&#8221;, &#8220;var1=val1&#038;var2=val2&#8221;);<br \/>\nreq2.process = function(res){<br \/>\n  window.alert(res.responseText());<br \/>\n}<br \/>\nreq2.send();<br \/>\n[\/js]<\/p>\n<p>You&#8217;ll note that this code is much simpler and neater than having to create a new class each time you want to do something different with the result you get from the server.<\/p>\n<h3>Conclusions<\/h3>\n<p>This is by no means an exhaustive list of the cool things that JS can do that Java has trouble with or does less well yet it is a substantial list with some very powerful features. Perl can also do just about everything in this article and there are probably other languages that can too but Java, C and C++ are not among those languages.<\/p>\n<p>Something else to note is that the two features that I consider most powerful (Multiple inheritance and the ability to edit classes on the fly) are made possible because JS supports function literals which is what sparked Joel&#8217;s article in the first place. The simple act of allowing you to create a function in the same way as a variable and then pass it round as if it was a variable gives JS immense power which Java and it&#8217;s ilk just do not have.<\/p>\n<p>JS used to be a language confined to just the HTML page but is is now growing beyond that. JS is used to power FireFox extensions, Mac OS X Dashboard Widgets and Yahoo Desktop Widgets (or what ever Confabulator is now called) as well as other non-web applications. Considering how powerful the language is it seems a shame that most people don&#8217;t realise what it can do or that it has now broken free from the HTML page. I have no doubt that we will see JS branch out into even more applications soon and I for one am really looking forward to that.<\/p>\n<p>[tags]Java, JavaScript, Programming[\/tags]<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Something that has annoyed me for a long time is that JavaScript is looked on by many people as just being a stripped down version of Java. You take Java, you take out most of the features and you get JS. This is completely wrong. The two are two completely different languages which follow different [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[12,16],"tags":[420],"series":[],"class_list":["post-259","post","type-post","status-publish","format-standard","hentry","category-computers-tech","category-programming","tag-javascript"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p7t9xK-4b","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/posts\/259","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/comments?post=259"}],"version-history":[{"count":1,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/posts\/259\/revisions"}],"predecessor-version":[{"id":7399,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/posts\/259\/revisions\/7399"}],"wp:attachment":[{"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/media?parent=259"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/categories?post=259"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/tags?post=259"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/www.bartbusschots.ie\/s\/wp-json\/wp\/v2\/series?post=259"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}