Functional Inheritance in Javascript

Javascript is a classless language. There are no classes in the language. However, we do have constructors that allows us to create class-like structures. We have talked about that in the past, and we have seen examples of how to create them. Although, personally I prefer a mixture of functions and objects without the need for constructors, it is sometimes necessary to have structures that can be extended to create even more powerful objects based on previous work without having to modify that previous work. This re-usability is, after all, one of the great benefits of Object Oriented Programming.

Multiple instantiation is also a concern of many. Quite often when I talk about the benefits of using pure objects rather than class-like structures, or data types (as I recently discovered some people call those class-like structures) people ask about multiple instantiation. People think you need to create an instance of, lets say a fade object per each element you want to fade. This is not true; You can manage to fade many elements simultaneously using a single object, but an explanation of how to achieve that is far beyond the scope of this post.

So, how do you create multiple instances of objects without using class-like structures and the new operator. And more importantly, how do you extend these objects?

Lets look at this in two parts. First, lets consider how to create multiple instances of an object. To do this, we will use functions. Look at this example:

var obj = function(){
    var private = 'private val';
    return {
        public : 'public val',
        method : function(){
            alert('I am method');
        }
    }
}

var o = obj();
alert( typeof o);

Now, create a second object and compare them to see if they are the same object:

var o2 = obj();
alert(o === o2);

What happened here?

Simple, two objects were created from the same “stencil”. These are two object that share nothing other than the fact that they were created using the same function. This is important because the private in o is not the same private in o2. In a practical example this could mean that each object can hold a reference to a different DOM node and modify it independently from other objects created with the same function. These objects don’t share a prototype, in fact they don’t even have one:

alert(o.prototype);//undefined

Interestingly enough they do have a __proto__ since they inherit from Object:

alert(o.__proto__);

So we could extend Object’s prototype and this would affect o and o2:

Object.prototype.fromObject = function(){
    alert('from Object');
}
o.fromObject();

In fact, it would affect any object in the page:

var a = [];
a.fromObject();

Even functions!:

var f = function(){
    
}
f.fromObject();

This is something you would usully not want to do in production, but it is an interesting thing non the less. This of course is not exclusive of creating objects with functions. You can do the same thing with mostly anything else. As long as you modify the Object’s prototype, you will find the same behaviour, and there are interesting things that can be done with this. But the only reason I touched on this is to demonstrate that o and o2 are in fact objects.

What about inheritance?

Inheritance can be easily accomplisehd. The idea is create the object that you want to extend and then add stuff to it:

var extendedObj = function(){
    var o = obj();
    o.newMethod  = function(){
        alert('new Method');
    }
    return o;
}
var exO = extendedObj();
exO.method();
exO.newMethod();

We have just extended Obj.

There it is, functional inheritance.

Now, before you people kill me, I am aware that a new object is created every time a new instance is created. When using constructors, all objects created with the same constructor share the prototype of that Object. This reduces memory usage. In this case, memory could be a problem if you are using too many instances of an object. Like I’ve been saying lately, it is always a matter of using the right tool for he right job. I’m just presenting those tools, it is up to you to decide which is the best for you to use.

4 thoughts on “Functional Inheritance in Javascript

  1. Hola.
    Me encantan tus articulos, los leo todos, bueno casi tudos, los que estan en ingles no jejeje.
    Te expresas muy bien, se ve conoces sobre el tema, pero no tendras la version en español de los articulos que escribes en ingles?

    • Hola,
      Hace unos meses decidí hacer el experimento de escribir en inglés y ver que tan bien me iva con el blog en inglés. Hasta ahora parece ser que tiene buena respuesta. Las visitas y los comentarios aumentaron un poco y creo que lo seguiré escribiendo en inglés. Pero también me gustaría tener el contenido disponible en español, ya que como tú hay quienes solo leen en español. Hasta hace unas semanas estaba buscando un buen blog en español para publicar las traducciones de mis artículos. Si conoces de alguno que tenga buen contenido y una buena comunidad, te agradecería me lo hicieras saber.

      Saludos y muchas gracias por seguir al pendiente del blog. Mientras tanto encuentro donde pulicar las traducciones, voy a traducir algunos de los posts y publicarlos aquí directamente.

    • Todos somos aprendices en este mundo. Sin duda que es una elección personal, pero hasta hoy no he encontrado un buen lugar para publicar, por eso es que preguntava. Mi objeción con ambos, maestros del web y cristalab es que estos no son dedicados exclusivamente a programación. e publicado anteriormente en maestros del web y no tengo problema alguno con volver a publicar ahí, pero esta vez andaba buscando algo más orientado de forma exclusiva a programadores y no solo a la “gente geek”, Voy a checar sentido web y ver si es lo que busco. Gracias.

Comments are closed.