0

I am learning JavaScript and this is my 1st week :)

var Module = (function () {
    // code
    var publicMethod = {};

    var privateMethod = function(someStringToBePassed) {
        debug("I love USA. "+someStringToBePassed);
    }

    publicMethod.someFunction = function() {
        privateMethod("USA is sexy");
    }
    return publicMethod;
})();

debug(Module.someFunction());

I am executing this in Sublime. I am seeing the following result.

--> I love USA. USA is sexy
--> undefined 

Please explain why I am seeing undefined here.

[Finished in 0.0s]

Please tell me why I am seeing "undefined" in the results

1
  • 1
    It's because you're calling someFunction and then immediately passing the result to debug. Either remove the second debug, or replace the first debug with a return. Commented Feb 1, 2017 at 21:21

2 Answers 2

1

You're not returning anything from someFunction. Try this:

Now someFunction returns the value of privateMethod. privateMethod returns the constructed string.

var Module = (function () {
// code
var publicMethod = {};

var privateMethod = function(someStringToBePassed) {
return "I love USA. "+someStringToBePassed;
}

publicMethod.someFunction = function() {
return privateMethod("USA is sexy");
}
return publicMethod;
})();

debug(Module.someFunction());

Sign up to request clarification or add additional context in comments.

2 Comments

Hey Thomas, Thanks for the reply. If I replace Module.someFunction() with Module.publicMethod() or Module.publicMethod, it gives me an error. Is there any reason why I can't refer publicMethod outside
When your code executes, the Module object gets reference to publicMethod object, since you are returning it from the self-invocated function. So, Module have access to the properties of publicMethod object only (for your example it's only someFunction). You can find more info just searching for "javascript module pattern". some example is here - addyosmani.com/resources/essentialjsdesignpatterns/book/…
0
var Module = (function () {
//code
   var publicMethod = {};

   var privateMethod = function(someStringToBePassed) {
        return ("I love USA. "+someStringToBePassed);
    }

    publicMethod.someFunction = function() {
      return  privateMethod("USA is sexy");
    }
    return publicMethod;
})();

var sample = Module;
console.log(sample.someFunction())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.