Archive for the ‘JavaScript’ Category

Improving prototypal inheritance in JavaScript with a surrogate class.

Posted on October 29th, 2013 in JavaScript | No Comments »

A friend of mine encountered this page by Michael Bolin, author of Closure: The Definitive Guide. It’s a very great writeup that distills a lot of JavaScript edge-cases and “gotchas” for a person just starting to get advanced in the language. I would have appreciated something like that back in the day and like most just learned it slowly through experience and bug-bashing over the years.

Though the page did cover prototypal inheritance well and it’s powerful ability to do pretty much everything that regular inheritance models of languages like Java can do, one small bit that the page didn’t cover was trying to call super on a parent class. The issue is that there is no built-in “init” method on a JavaScript constructor. The simple act of initializing a “class” in JavaScript both creates the object and calls its setup routine inside the class. This might be perfectly fine in most people’s day-to-day Javascript but if you ever need your parents class to do some additional setup work for example in the case of a factory pattern, you need this support. JavaScript frameworks like Backbone.js and jQuery invented their own ways to solve this issue but it’s important to know the minimum amount of effort to solve this problem without relying on a 3rd party framework.

The answer is to create an empty “surrogate” class to hold the parents prototype. That way when it is initialized, you have the chance to run the contents of constructor when you’re good and ready:

function Mammal(obj) {
    this.name = obj.name || 'Anonymous Mammal';

    // Basic conditional code you normally couldn't do.
    if(obj.pouch){
        this.category = 'marsupial';
    }
};

Mammal.prototype.legs = 4;

var lion = new Mammal({ name: 'Lion' });
var tiger = new Mammal({ name: 'Tiger' });

// This middle constructor is required because we can't instantiate `Mammal` directly as `Marsupial`'s prototype
// or else it would run through its "initialize" stuff too early.
function Surrogate(){};
Surrogate.prototype = Mammal.prototype;

function Marsupial(obj) {
    Mammal.apply(this, arguments);
};

Marsupial.prototype = new Surrogate();
Marsupial.prototype.pouch = true;
Marsupial.prototype.legs = 2;

var kangaroo = new Marsupial({name: 'kangy'});

The above example is highly contrived but you can see that you can actually push off a bunch of responsibility from the child class to its parent. Which means less setup work for each child and the ability for the parent class to decide the “DNA” of the child based on the parameters passed in. For example if this was a vehicle parent class, mixin the diesel engine class or if the child is a truck or hybrid engine if the child is an electric car.

Convert Epoc time to a real local date in JavaScript.

Posted on December 7th, 2012 in JavaScript | No Comments »

Lots of times, when you use APIs they are using Epoc time to specify a date (which is the number of seconds that have elapsed since midnight (UTC),January 1, 1970). This post isn’t to explain why Epoc is that date, though interesting. Here is some quick JS to convert that to a real human date in your local time zone:

function realDate (epoc){
    var d = new Date();
    d.setTime(epoc * 1000);
    return d;
}

realDate(1354908817);
// returns Fri Dec 07 2012 11:33:37 GMT-0800 (PST)

Older is sometimes better or why I use an old version of jQuery.

Posted on July 21st, 2011 in JavaScript, jQuery, zepto | 1 Comment »

For the last year or so I’ve been predominantly focused on mobile web applications. While I’m a big fan of jQuery, at it’s current revision of *32.18 KB (compressed and gzipped) I think it’s generally too big for the mobile web. That’s when I discovered Zepto, a jQuery-like library that features 90% of the same functionality at a weight of 4.8 KB (compressed and gzipped). Life was good again and I resumed working with iOS and Android web apps, bidding IE adieu.

Fast forward to now and I need to make some general web pages again for a project and I need to support IE once more. These pages have some light-to-moderate js functionality and though I could write a small library from scratch, I’d be a fool in wasting so much time, though minimally, I only need:

  • Cross-browser event support
  • Cross-browser ajax support

Though one does arguably write faster and more concisely (smaller file size) if one has:

  • A chainable API
  • A CSS selector engine

The answer? Use an older version of jQuery. jQuery 1.2.6 for example is 17.18 KB (compressed and gzipped). Almost half as small as the current version. It gives me all four requirements above. Every version of jQuery has been battle-hardened against the most finicky older browsers and the newest batch of browsers aren’t really causing too much trouble. I had been writing with Zepto in Chrome initially when I made the switch to test in IE. I made the switch to 1.2.6 without issue. IE and all browsers are happy.

While I would love to take credit for thinking this through, it actually happened by accident. I referenced jQuery version 1.2.6 from Google’s CDN instead of 1.6.2.

I’m sure someone’s going to comment how I’m missing some major optimizations in later versions, but after trying the project out, I already have split second performance using an old build. If I start doing crazy animations or need .live, I’ll move up some revisions. If you do plan to try this out for yourself, know that jQuery 1.3 (20.08 KB) is when Sizzle was introduced and in jQuery 1.6 a lot of the API was modified or had signature changes (nothing that’s affected me so far).

Here’s a list of some versions along with their file sizes. Check the blog for more details.
1.6.2 (32.18 KB) – misc small bugfixes
1.5 (30.12 KB) – ajax timeout and abort
1.4.2 (24.86 KB) – .delegate
1.4 (27.25 KB) – extended .live support
1.3 (20.08 KB) – Sizzle and Live
1.2.6 (17.18) – 100% faster events
1.2 (17.21 KB)

And don’t forget if you’re using Google’s CDN (a good idea), always fallback to your own version, too, just in case.

*2.6.1, I use Charles Debugging Proxy for measurements.

Docco: cool JS documentation generator

Posted on June 27th, 2011 in JavaScript | 1 Comment »

I noticed both backbone.js and spine.js are using it:

http://jashkenas.github.com/docco/

Creates pages like this:

http://documentcloud.github.com/backbone/docs/todos.html

JavaScript compression: Google Closure Compiler vs UglifyJS

Posted on April 21st, 2011 in JavaScript | 1 Comment »

After setting up a make / jsmin build system for concatenating and minifying CSS files I looked around to see what’s the best compresser to do the same with JS these days and it looks like it’s a toss-up between Google Closure Compiler and UglifyJS.

I’ve heard from two different developers about problems caused by Google Closure compiler: one edge-case where it incorrectly rewrote some JS, and the other about having to write your JS a certain way for maximum efficiency. After reading up on UglifyJS here and seeing how both jQuery and Zepto are now using Uglify (jQuery moving from GCC to Uglify 3 months ago), I think I’ll give UglifyJS a try and let you know how it goes. The readme file that comes with Ugly is in both html and org formats. I’m liking it already…