user6797078
user6797078

Reputation:

JavaScript - Calling a variable object inside of a variable object

I'm new to StackOverflow and coding. I want to know if it is possible to call a variable object within a variable object in JavaScript.

Maybe something like this:

var info {
    name: function() {
              document.write("Jordan");
              last: function() { 
                        document.write("Baron");
                    }
          }

So when you call info.name(), it does document.write("Jordan), and when you do info.name().last(), it does document.write("Baron")

If it's a stupid question, be brutal. I want to learn from my mistakes.

Upvotes: 1

Views: 42

Answers (1)

DamianoPantani
DamianoPantani

Reputation: 1376

This is not a stupid question, a very good one in my opinion. Try this:

var info = {
    name: function() {
        document.write("Jordan");
        return {
            last: function() {
                document.write("Baron");
            }
        };
    }
}

info.name();
info.name().last();

Fiddle here

You have to return an object which contains a function to have a possibility to call it. The only con of code above is that document.write("Jordan"); is called in both cases - when info.name(); and info.name().last(); are invoked. If it's not an expected behavior, try this:

var info = {
    name: function() {
        return { 
            first: function(){
                document.write("Jordan");
            },
            last: function() {
                document.write("Baron");
            }
        };
    }
}

info.name().first();
info.name().last();

Upvotes: 1

Related Questions