My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Friday, December 28, 2012

A Cross Platform Inherit Function

This (apparently non working) gist gave me the hint. Stuff I've been dealing with for a while, finally used to bring an Object.create(firstArgOnly) cross platform/engine/client/server code that works. The name? inherit()

More Reliable Than Object.create()

The reason I didn't even try to polyfill the ES5 Object.create() method is quite easy: it is not possible to shim it in a cross platform way due second argument which requires descriptors features, highly improbable to simulate properly. Even if browsers support the create() method, inherit() guarantee that no second argument will ever be used so we are safe from inconsistencies within the function.

Forget hasOwnProperty !

Yeah, one of the coolest things about being able to inherit from null is the fact not even Object.prototype is inherited so we can create real empty objects without worrying about surrounding environment, 3rd parts obtrusive libraries, and the boring and slow obj.hasOwnProperty(key) check.
// some obtrusive code
Object.prototype.troll = function (up) {
  throw up;
};

// empty object in every browser/env
var dict = inherit(null);
dict.anyKey = anyValue;

// later on ...
for (var key in dict) {
  // only 'anyKey'
}
That's correct, objects that inherit from null are not affected by the Object.prototype ... really, we cannot even print them without defining a toString method!

Update: On IE DontEnum Bug

Unfortunately the fact IE does not enumerate toString and other native Object.prototype names is not solved here for the simple reason here we are not solving that problem, here we are solving inheritance. However,I think is a must know that even objects created via this function needs an extra loop or something like this:

Not Only Null

This function should just work with anything we might need to inherit and we can also inherit from inheriting objects without problems. Consider this an end of the year tiny present just to remind some basic concept about JS that is still valid: Objects inherit from Objects and that's pretty much it :) Enjoy and see you next year!

1 comment:

Christopher said...

This is really great, as usual. Thanks Andrea!