One of the great things about reading through Douglas Crockford’s site is that you get to learn about how certain things like prototypal inheritance was implemented prior to ECMAScript 5. Since then Object.create()
made its way into JavaScript and has been available in most modern browsers for a while. If you haven’t read through Crockford’s site or seen how prototypal inheritance was done before, here is a quick overview:
You can click here to test out the code yourself. As you may have noticed, the key to prototypal inheritance is as follows (please ignore the names of these prototypes disguising themselves as classes :smile:):
SubClass.prototype = new Class();
Unfortunately, at times you may not be able to safely execute the constructor of the prototype which is being inherited (which in this case would be Class
). In order to get around it, you can create a surrogate function whose prototype will become that of the prototype to be inherited:
function SurrogateClass(){}
SurrogateClass.prototype = Class.prototype;
SubClass.prototype = new SurrogateClass();
Unfortunately, it isn’t the most memorable sequence so let’s turn this into a simple function:
function inherit(Class, SubClass) {
function SurrogateClass(){}
SurrogateClass.prototype = Class.prototype;
SubClass.prototype = new SurrogateClass();
}
Finally, let’s minify it:
function inherit(C,S,p){function O(){}O[p='prototype']=C[p];S[p]=new O}
OK, so this is minification to an extreme since I placed p
in the function’s signature. I also went a bit far by sketchily defining p
in the left-hand side of the assignment of the prototype to the surrogate function. Even though the above code seems to work, just to be safe, here is a slightly longer, more trustworthy definition:
In the end, both of these definitions are extremely small so I’d say even prior to ES5, prototypal inheritance wasn’t as difficult as one might have thought. š