Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14774

Why does a function in my object return undefined?

Consider this code:

var MSE = {
    Module : {}
};

MSE.Module = (function() {

    'use-strict';

    var app = {

        tabsPre : function() {

            var tabsPre = {
                init : function() {

                },
                changeTab : function(arg) {
                    return arg;
                }
            };

            tabsPre.init();
            return tabsPre;
        }
    };

    return app;

})();

console.log( MSE.Module.tabsPre() );
console.log( MSE.Module.tabsPre().changeTab() ); // undefined
console.log( MSE.Module.tabsPre.changeTab() ); // Uncaught TypeError: MSE.Module.tabsPre.changeTab is not a function

I am trying to access changeTab() in the tabsPre object, but I don't seem to be able to. The last two console.log statements aren't giving me what I had hoped for. How can I do this?

Here's a JSFiddle: https://jsfiddle.net/xhb16qL6/

In the first console.log, I can see the function is there:

enter image description here

Any help or guidance on what I'm doing wrong would be great. I'm probably having a dumb day and can't see it.

Thanks, Mikey

Upvotes: 0

Views: 84

Answers (4)

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

JavaScript dosen't check for the number of arguments.

Suppose I have a method, say add and defined like this:

function add(arg1, arg2){

}

I call this method like in 3 different ways, lets assume:

1) add(1,2)   // Works just fine

2) add(1,2,3) // My third argument is ignored.

3) add(1)    // 2nd expected parameter is taken to be `undefined`

Your problem is scenario number 3.

Your changeTab method expects ONE argument. If you dont pass any in your call to changeTab, you see undefined.

Upvotes: 2

Joe Fitter
Joe Fitter

Reputation: 1309

console.log( MSE.Module.tabsPre() );

this logs the tabsPre object you are returning

console.log( MSE.Module.tabsPre().changeTab() );

this logs the result of MSE.Module.tabsPre().changeTab() which is undefined as you didn't pass an argument

console.log( MSE.Module.tabsPre.changeTab() );

this causes an error as MSE.Module.tabsPre is a function, and therefore you cannot access properties of it, as they don't exist

Upvotes: 2

khakiout
khakiout

Reputation: 2400

The changeTab () function expects an argument. The code then returns the argument passed once it's called. Since you didn't pass an argument, then undefined is returned.

Try passing an argument :)

Upvotes: 1

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

ChangeTab return the args its passed to it and it print undefined because you didn't pass any arguments, try:

console.log(MSE.Module.tabsPre().changeTab("args"))  //"args"

Upvotes: 2

Related Questions