Thursday, March 16, 2006

Closures make JavaScript OO

  • "The new keyword creates an object that class constructors run inside of, thereby imprinting them
  • Functions are always closures (combine w/ previous rule to create OOP)"
Has Alex lost the plot? What do closures have to do with Object Oriented Programming (OOP or OO)?

Objects don't really exist in JavaScript: an object = a constructor function. So when you say:
var Richard = new Person();
you are creating a new instance of the Person function. Consider the following:
  1. function Person() {
  2. this.name = "Joe";
  3. }
  4. function Employee() {
  5. Employee.prototype = new Person();
  6. Employee.prototype.constructor = Employee;
  7. }
  8. var joeEmp = new Employee();
  9. alert (joeEmp.name); // shows "Joe"
JavaScript first looks at the properties of joeEmp then if it doesn't find a name property it looks at the prototype property of the Employee function. If the object that the prototype property points to has a name property it will return that.

This works because Employee is a closure (in line 8) so inherits the environment and variables in which it was called i.e. the name property of the Person class:

function Employee() -> function Person()

Note also line 6. This is important - otherwise Employee forgets what it is! It starts thinking that it = Person! Normally we do not have to set the constructor property but when we reassign the prototype property we need explicitly to declare what this function is. This is done by specifying the constructor property.

I found Kevin Linsey's post on inheritance very helpful in writing this and intend to read more about superclassing, something that doesn't normally exist in JavaScript, but for which Kevin has a solution.

Wednesday, March 15, 2006

Closing my JavaScript not my brain

"Functions are always closures"
is Alex's next point. What is a closure? Jibbering provides the long answer. The short answer Simon Willison discovered when writing a solution to the old problem "I want to run lots of functions onload but keep forgetting when and where I've assigned them":
A closure is function that returns a function together with the variables from the environment in which the closure was created.
OK that didn't sound any clearer. Simon's post explains this much better than I can but I have run into the problem he is tackling so often that I was interested enough to read the solution in depth.

His answer is to create a function that piles up a list of the functions that will be executed onload. I'll let him explain how. Suffice to say it uses a function that is a closure.

So closures - pretty smart things really.

Thursday, March 02, 2006

Constructing my objective

Alex's next point concerns object creation:
The new keyword creates an object that class constructors run inside of, thereby imprinting them
Remember that an object is just a function, as in Dion Gillard's car example:
function Car(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
this.toString = function() {
return this.make + " " + this.model + " (" + this.year + ")";
}
}
var myCar = new Car("Subaru", "Forester", 2003);
alert("My car was made in "+ myCar.year);
What Alex means (as he describes in answer to a comment later) is that when you create a new object based upon a constructor, the object becomes the focus of the this property in the constructor. The effect is to imprint the new object with the properties and methods of the constructor.

Now, as a bit of background before I tackle the next point I had to do some more reading of Dion's fantastic Better JavaScript guide. That gave me at least a slim grasp on:
  • methods of objects
  • the prototype property
  • inheritance and superclassing
This gave me enough of a start to be able to understand the idea of functions being declared inside of functions. More in my next post...

Wednesday, March 01, 2006

Making a hash of accessing properties

Continuing my plunge into a deeper knowledge of JavaScript (based upon Alex's pointers) today I met:
"The dot operator is equivalent to de-referencing by hash (e.g., foo.bar === foo["bar"])"
Eh? In English please? OK to de-reference means to retrieve the value from a reference (thank you, Wikipedia). So what this is saying is: you can access the properties of an object by the "dot" notation or by the "square brackets" notation.

Jim Ley has a fantastic guide to using the square brackets notation which "gets very little coverage in most books on JavaScript and [...] seems to leave novice JavaScript programmers unaware that they even have this option".

This is a little gem! I will definitely be using this!

Tuesday, February 28, 2006

Re-learning JavaScript cont.

Continuing on Alex's points about JavaScript: Number two:
"Every object is always mutable"
This means that objects, defined as functions or constructors, can be re-written or their properties modified at run-time.
In a class-based language a class is defined in the source code and is absolutely fixed while the code is executing. In JavaScript all objects are mutable. Any property can be added to any object at any time and prototypes can be extended, replaced, swapped and so on. (Richard Cornford, "Private Static Members in JavaScript")
So OO is not implemented as strictly in JavaScript as in other programming languages but equally that makes it flexible. Nice.

Monday, February 27, 2006

Object Disoriented

IBM is pushing Server-Oriented Architecture (SOA) in Lotus Notes 7 which seems a natural extension (or generalisation) of web services, the idea behind which seems to be self-contained very targeted programs accessible by a variety of media.

Before I can get my head around all that, however, I'm trying to understand Object Oriented Programming (OO). I know a bit about JavaScript and was just starting to learn about OO. Then I came across a post by Alex Russell about JavaScript that left me crying out "eh?!". However, other posts from Ajaxian were to come to my rescue! I shall tackle one of Alex's points a day, I think. Number one:
"Everything in JavaScript is an Object. Even functions"
Dion Gillard has posted a helpful "guide to JavaScript or Java developer", notably: Better JavaScript objects, which shows how JavaScript objects are formed and that they can have functions as properties. His next post ("Better JavaScript Functions") starts to explain scope in the context of OO (and JavaScript) and concludes by explaining that constructors are used in place of class declarations in JavaScript.

So now I know: even function are objects. Now where can I use that?

Sunday, February 26, 2006

More on JSON

Just read a fantastic article on JSON by Steve Maine. It tells you what JSON is, what it looks like, and how it is being used. It progresses to comparing XML and JSON, as does this article. However, Steve's article is obviously written from the perspective of one used to using XML in full-on data exchange. Commenting on the lack of Namespace support (which would allow me to come to a JSON string and say explicitly that the telephone number property will always be a number, say) he concludes:
"AJAX and JSON are at the point where XML, SOAP, and XML-RPC were about 5 years ago; they just haven't realized that yet"
Or be it the case the overhead of finding/devising a namespace then developing in line with that is too much for small software houses such as the one for which I work. JSON offers a quick but adaptable solution to the masses... even if we do come to regret it when asked to make our rich applications work with other applications.

Clients will always fail to see the need for flexible systems. It is our responsibility to provide at least some of the flexibility that any system requires during its adoption/growth stages. This is something for which all the developers at my workplace feel a large burden of responsibility and for which our company is known. However, there is a limit. There will always be a trade-off of future-proofing against current budgets.

For me, at least, the overhead of namespaces and XML is that limit. I can see myself using JSON in the future but will be most unlikely to progress to full-on XML.

Groups and Individuals

When I was at university I read and talked a lot about "Social Capital". I also took a couple of modules in Organisational Behaviour - sociology plus psychology kind of waffle...

... or so I thought. Today I was reflecting on being a member of a group. As a member of any group we must suppress those elements of our personalities that are at odds with the norms of the group.

When we are about to move groups we slowly realise those aspects of our personality we had suppressed; those norms of the group with which we never did agree but put up with for the benefits of social capital. To those in the group we seem increasingly "spiky" as we start not to fit in some aspects.

Sadly, most groups at this stage will isolate that group member in the hope that the "infection" (or behaviour contrary to the norms of the group) will not spread to other members. I say sadly since in the period of leaving one group and applying for membership of another we are without - and yet in most need of - social capital i.e. support.

This is why we are members of multiple groups: work; the swimming club; church, etc. Yet the years post World War II have seen a diminution of forms of social capital with the virtual abolition of unions, etc.

I argued it at uni and I maintain it today: the answer has been with us all along: the church.