Anything can be … actually anything

Ok, this may seem pretty silly. But I think it demonstrates an interesting point:

Not only is everything an object in JavaScript. A single object can also be anything in itself.

//Let's create an object ...
Anything = function ( food )
{
    var text = 'Something really meaningful'
    this.toString = function ()
    {
        return text;
    }
    this.constructor.number = 42;
    this.constructor.toString = function ()
    {
        return text + ', like ' + this.number;
    }
    return  text + ' with ' + food +
            '<br /><em>Mmmhhh ... ' + food + ' ...</em>';
}

//It can be a constructor for new object instances
document.write( new Anything ()    + '<br />'  );

//or an object collection of other values
document.write( Anything.number    + '<br />' );

//or a function with parameters and a return value
document.write( Anything ( 'pie' ) + '<br />' );

//or a simple value
document.write( Anything           + '<br />' );

//Anything can literally be anything...

Here I created a single object that can act in four different roles.

That may not seem very useful here but I just wanted to demonstrate the flexibility of JavaScripts object system and I’m sure this can be quite useful in some library classes that can expose different properties or methods when uses in multiple different ways like Anything here.

And yes, I also did it just for the fun … And the pie.

  1. rxq reblogged this from techpriester
  2. techpriester posted this