chris clarke
software development that works…or something
Private, Public and Static in JavaScript
September 22, 2007 on 4:30 pm | In JavaScript | No CommentsJavaScript doesn’t have keywords for making things private, public or static like other languages but it is possible - unfortunately like most things in JavaScript it’s possible in several different ways!
Public and private access in JavaScript
To declare a method public in JavaScript you can assign it to the prototype:
// The class
Monkey = function () {};
// The public method getBananas
Monkey.prototype.getBananas = function() { ... };
..or you can also assign it to this in the constructor:
Monkey = function () {
this.getBananas = function () { ... };
};
To make things private you can take different approaches aswell. You can just define them to a var in the constructor:
Monkey = function () {
var privateMethod = function () { ... };
};
…or you can use the approach Carlos Villela suggests and define your public and private methods in different objects inside the constructor and return the public object:
Monkey = function() {
var private = {
privateMethod : function () { ... }
};
var public = {
getBananas : function () { ... }
};
return public;
}();
Static members in JavaScript
Static members are easy, you just define them directly on the class:
Monkey.MAX_BANANAS = 120;
Monkey.swingFromTree = function () { ... }
Tool Support For JavaScript
August 6, 2007 on 12:57 am | In Tools n Stuff, Testing, JavaScript | No CommentsOh dear, what happened to my clever navigation and code-completion? The IDE support for JavaScript is still catching up with Java, if you have only small amounts of JavaScript you’ll be fine with TextMate or something similar. But for large class-based projects you’ll need something else.

The best thing at the moment is IntelliJ, its currently the only thing out there that can navigate across a codebase. With Aptana or Eclipse, if the method exists in another file it cannot navigate to it and you’re forced to resort to searching in files ending with *.js. Second best is Eclipse 3.3 with the JSEclipse 2.0 pre-release installed. (I’m really impressed with Eclipse 3.3 - its improved in several places - but I especially like the Quicksilver style Ctrl-3 shortcut).
How hard can unit-testing JavaScript be?
On the surface of things JavaScript seems to have a lot of the same tools that Java has for unit-testing. JSUnit is the JavaScript equivalent of JUnit and JSMock the equivalent of JMock.
The syntax of JSUnit is fine, its pretty much as you’d expect and conforms to the XUnit conventions. The key bit that’s missing is the fast feedback. When working on a class you want to be able to run the test often so you can see the immediate effects of changes you’ve made and the let the test tell you exactly whats wrong. To run a test with JSUnit, I need to open the JSUnit test runner in a browser, load my test page and then run it. Once I’ve run it, assuming its failed I get a list of tests that failed - but not the reason they failed, I need to double-click - then I get an alert telling me why the test failed. It really interrupts your flow, especially when you’re flipping between multiple classes. If you’re using an IDE with a Browser Preview tab, you can get around this problem with a little JavaScript along the lines of:
var currentLocation = "" window.location;
window.location = "file:///.../testRunner.html?testpage=" currentLocation "&autoRun=true";
(Sorry plus signs don’t seem to show up - hopefully you can get the general idea).
I’ve got this working in Eclipse by installing the EclipseHTMLEditor plugin and including the following common bit of code in all JSUnit tests:
var currentLocation = "" window.location;
if (currentLocation.indexOf("cacheBuster") < 0) {
window.location = "file:///.../testRunner.html?testpage=" currentLocation "&autoRun=true";
}
Now a test can be run by just clicking on its Preview tab.
Making a Mockery
JSMock is kind of good - at least someone’s written a mocking framework for JavaScript. As soon as you start to use it - you realize that it is by know means a mature piece of software.
It doesn’t give you any kind of useful messages, for example it will say ‘Unexpected Arguments’ but won’t tell you what the actual arguments were against the expected arguments. Similarly for an unexpected invocation, it won’t tell you what has been called and what was expected to be called. The other missing piece is support for literal objects - JSMock gets it wrong if you pass a literal object as an argument. This is basic stuff - thankfully the code is still quite small and I’ve found myself adding a lot of these features myself just to be able to use it.
The cool thing about JSMock is that because JavaScript is such a flexible language you don’t need to put your method calls in strings like in JMock 1 and you can keep using literal language (unlike in JMock 2):
server.expect().request('/index.jsp', {
method: 'get',
parameters: { userId: 'fred' },
onSuccess: function () {}
});
Another cool thing is that if I have static objects as collaborators I can mock those too:
var mockThing = mockControl.createMock(Thing);
// substitute the mock Thing for the real Thing
Thing = mockThing;
eXtreme JavaScript
August 5, 2007 on 11:32 pm | In eXtreme Programming, JavaScript | No CommentsOver the past few months I’ve been working a lot with JavaScript. The language is very deceptive as it has C-style syntax, and is mostly written with little regard to good programming practice. However, it turns out to be quite a good object-oriented language which can lend itself to some very elegant code.
The language itself has a fair few problems for your average extreme programmer. For starters it’s a dynamic language so a lot of errors won’t turn up until you run it, and because of its tendency to not throw Exceptions (which do exist in JavaScript), things may just quietly go wrong. Code conventions don’t seem to have been established yet and there are an awful lot of different ways to do the same thing in JavaScript, for example declaring a class can be done like this:
function Monkey() {
// constructor
this.getBanana = function() {
// ...
};
this.eatBanana = function() {
// ...
};
}
…or it can be done like this:
function Monkey () {
// constructor
}
Monkey.prototype.getBanana = function() {
// ...
};
Monkey.prototype.eatBanana = function() {
// ...
};
or this…
Monkey = {};
Monkey.prototype = {
getBanana : function() {
// ...
},
eatBanana : function() {
// ...
}
};
… or you could even do it like this (although you’d have to be mad):
Monkey = function() {
// constructor
};
Monkey['eatBanana'] = new Function("alert('eating banana')");
Monkey['getBanana'] = new Function("alert('getting banana')");
If you are doing extreme programming it can be much harder to come up with agreed standards just because there are so many different ways of doing things. This also makes refactoring a much more subjective affair and can lead to churn if developers enter the vicious circle of refactoring other peoples code to their preferred style. Also, its very easy to do (and it seems fun for some people) clever and complicated things in JavaScript which means simplicity of the codebase often suffers.
Shared Coding Standards
This makes me think when dealing with JavaScript it is very important to have shared coding standards agreed by the whole team. For the benefit of rooting some values of simplicity in the team its probably a good idea to agree a set of things that just shouldn’t be done (i’m thinking about the needlessly complicated things here). Similarly, when CSS and DOM manipulation are involved - the team should agree standard ways of doing things.
Powered by Cheese.
RSS Entries Feed.
RSS Comments Feed
^Top^