The Blurb: This is mostly just a bit of fun and in form of some rough notes as I’ve been sticking my head into a few JavaScript books and thought I’d write down what strikes me as odd/interesting along the way. Of course, I’ve written some bits of JavaScript but I’ve never really sat down and read up on it. I’m not trying to be definitive and nor am I trying to take a particular view – just poking around
OMG #26 – Partial Application & Mapping
Nothing radical in this OMG, it’s really one for me to remember to try to “think functionally” and that came home while reading about map and partial application which I’ve tried to do here via ES5’s bind function;
// I can write a function map which performs some function on // every array element. function map(func, array) { var result = []; for (var i = 0; i < array.length; i++) { result.push(func(array[i])); // func may well see "undefined". } return (result); } // I can then "bind" a version of that function such that its invocation context // and first parameter are hard-wired var squareMap = map.bind(null, function (x) { return (x * x); }); // And then apply that to some array of values. console.log(squareMap([1, 2, 3])); // logs 1, 4, 9 // And then move up a level with an array of arrays console.log(map(squareMap, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])); // logs 1,4,9....
Reference: Haverbeke, “Eloquent JavaScript” Page 90-91
OMG #27 – “Self Defining” Functions
This one came from a discussion with my legendary colleague Mike Ormond where we were talking about doing something simple like having a unique object key stored in each object of a particular type.
You start off with something like;
var MyType = (function () { var sharedId = 0; var ctor = function () { this.id = sharedId++; }; return (ctor); })(); var one = new MyType(); console.log(one.id); console.log(one.id); var two = new MyType(); console.log(two.id);
and then I wonder if I can hide the id so it isn’t a straight property that can be changed by someone assigning a new value to it for instance and so I hide it behind a function;
var MyType = (function () { var sharedId = 0; var ctor = function () { var localId = sharedId++; this.id = function () { return (localId); }; }; return (ctor); })(); var one = new MyType(); console.log(one.id()); console.log(one.id()); var two = new MyType(); console.log(two.id());
Now, someone can still delete the id() function but my next thought was that it seems wasteful for every instance to have to have a different function just to get its id. Isn’t this where the prototype should help out? Couldn’t it take the burden of implementing that function?
To be honest, I think the answer is “no”. The prototype is shared between every instance and I’m looking for a piece of state which is unique to the instance so it feels like the only route left feels to be;
var MyType = (function () { var sharedId = 0; var ctor = function () { var id = this.id(); this.id = function () { return (id); }; }; ctor.prototype.id = function () { return (sharedId++); }; return (ctor); })();
although another option might be to defer making the id for the instance until it is first asked for but your object instances then get numbered differently;
var MyType = (function () { var sharedId = 0; var ctor = function () { }; ctor.prototype.id = function () { var id = sharedId++; this.id = function () { return (id); }; return (id); }; return (ctor); })();
and I guess that’s the first one that really is a self-defining function.
Reference: Stefanov, “JavaScript Patterns” Page 68
OMG #28 – This or That?
This is absolutely a re-statement of OMG #24. Why am I repeating myself? Because I keep banging my head against this one and it’s probably one of the things that would really trip me up again and again. I’d go so far as to say that I really wish that JavaScript had no use of the word this whatsoever because it’s just confusing (to me, anyway
).
Where I’m being bitten by this the most is in event handlers. I do something that seems intuitive or, almost, second nature to me;
var MyType = function () { }; MyType.prototype.x = 0; MyType.prototype.y = 0; MyType.prototype.handler = function() { var sum = this.x + this.y; // Woops! }; document.addEventListener("DOMContentLoaded", function () { var button = document.getElementById("button"); var myInstance = new MyType(); button.addEventListener("click", myInstance.handler); });
and it’s once again my expectation that in my function called handler there will be a this pointer to make use of whereas when that function is called from the event handler, the this pointer can’t possibly be passed because it wasn’t part of what was given to the event handler in the first place.
It’s not “so hard” to fix this kind of problem with something like;
var MyType = function () { }; MyType.prototype.x = 0; MyType.prototype.y = 0; MyType.prototype.handler = function() { var sum = this.x + this.y; // Now ok 🙂 }; document.addEventListener("DOMContentLoaded", function () { var button = document.getElementById("button"); var myInstance = new MyType(); button.addEventListener("click", function () { myInstance.handler(); }); });
but it’s catching me out again and again
Reference: Stefanov, “JavaScript Patterns” Page 68
OMG #29 – Events
I don’t think this one is really JavaScript’s “fault” as such as I don’t think that the language has fully fledged support for events and so you’re left to model events as a list of function pointers.
Looking at something simple like a button, you end up with an onclick event which you can either handle by assigning a function to that property on the button or by using addEventListener to add your handler to the event.
document.addEventListener("DOMContentLoaded", function () { var b = document.getElementById("butt"); b.onclick = function () { var x = 10; } });
and in that snippet I used addEventListener to sync up to the event on the document whereas I used onclick = to sync up to the event on the Button.
Now, I thought I had this pretty well understood in that it’s fairly easy to understand that addEventListener is going to let the event have multiple listeners whereas doing the onclick = assignment is going to presumably overwrite any event listener that was already stored in the onclick property.
I thought I had it all sorted until I came to work with a “type” that I didn’t understand. I’d written code something like;
function SomeFunction() { var instance = new SomeoneElsesType(); instance.onchanged = function () { }; }
and this “SomeFunction” code runs many times in my application and I was quite happy with the idea that I was the only listener that would subscribe to this onchanged event and so it didn’t matter that I wasn’t using addEventListener.
That proved to be true until I figured out that the SomeoneElsesType turned out to implement a form of singleton pattern which meant that the onchanged property was effectively a singleton which meant that my overwriting of the event rather than using addEventListener actually did matter and I couldn’t get away with it.
What did I learn? Always use addEventListener even when you think that you don’t need it as otherwise you can get bitten by someone else’s implementation choices.
OMG #30 – “JavaScript, it’s just like everywhere!”
Number 30 will be the last of these “OMG” posts. They were just a bit of fun while I took some initial steps although I’d say that I’ve encountered most if not all of the 30 (ok, 29) many, many times over the last month or so which has seen me doing more work with JavaScript than I’ve ever done before.
Of course, I never needed to write any of these things down. JavaScript information and snippets and techniques and tools and libraries are all over the internet. There are examples at and and no doubt lots of other places so these were just a place for jotting down some of my own experiences but, for now, I’m done.
You can find the rest of these “JavaScript OMG!!” entries here