Friday, August 8, 2008

Basically because I don't know it... and I don't want to get aquainted with it!!! Maybe it is because I'm so accustomed to the Java language, maybe because I'm dumb, maybe for a combination of these and several other factors. Anyway, I'll post some tips and some scripts that, albeit very easy, drove me crazy simply because I couldn't find their right syntax.

If you need to create an object in Java you must have a particular class and call its constructor using the "new" keyword (Yes, we can also use a factory method, a creation method, the newInstance method of the class, or other stuff, let's not be pedantic):

But the interesting thing comes with methods. If you want to invoke a method in Java it must exist as public (yes, also default, or protected for subclasses, you could use reflection, I'm simplyfing for simplicity's sake!) in a class assignable to the object. In Javascript you simply add it:

addressObj.myOwnMethod = myOwnMethod;

If you want to call that method you use the syntax

addressObj.myOwnMethod();

BTW, all semicolons at the end of the lines are optional, just to make things weirder. And what happens when you call a method? you are really calling a function defined elsewhere, something like

function myOwnMethod() { ...}

If your function has parameters, its declaration would be something like

function myOwnMethod(par1, par2) { ...}

and if you want to call it you use the syntax

myObject.myOwnMethod(par1, par2)

What if you want to hide the parameters of the function you call, e.g. you ask a shipment for its cost, which is calculated on the basis of some attributes of the shipment itself? In Java you simply ask it to the shipment instance:

double shipmentCost = myShipment.getCost()

In Javascript you do the same, but it works in a slightly different way (maybe that's not the only one, but it is the only one I managed to get working). You have a method in the object without parameters, as one would expect, you have a function without parameters, as one would NOT expect, that gets called from the object when you invoke its method and it uses the "this" keyword... The "this" in a function!!! and it does not refer to the function but to the object that invoked it! how counterintuitive!

...// inside the definition of an object (if using a template=// or simply after the instantiation of an objectmyShipment.getShippingCost = getShippingCost...