Search code examples
javascriptoopobjectobject-literal

Methods and sub-methods in JS object literals


So if I declare an object in Javascript like so:

var myhouse = {
    room: {
        bed: function() { return "sleep"; }
    }
}

I can call:

myhouse.room.bed();

Can I make a method that's callable with just:

myhouse.room();

? I can't just say:

var myhouse = {
    room: {
        function() { return "stuff"; },
        bed: function() { return "sleep"; }
    }
}

It's invalid. So what am I missing? Is it even a good idea to do this?


Solution

  • You can't do it with a single literal, you need an extra assignment to set a property on a function:

    var myhouse = {
        room: function() { return "stuff"; }
    };
    myhouse.room.bed = function() { return "sleep"; };
    

    To make it a single expression, you could either use a IEFE

    var myhouse = {
        room: (function(){
            var room = room = function() { return "stuff"; }
            room.bed = function() { return "sleep"; };
            return room;
        })()
    };
    

    or the comma operator (horribly unreadable, but working):

    var myhouse = {
        // using myhouse as an already declared variable
        room: (myhouse = function() {return "stuff";},
               myhouse.bed = function() {return "sleep";},
               myhouse)
    };