More Than Five
More Than Five

Reputation: 10419

Invoking a function in a closure

I am trying to creae a simpe page closure like this:

page = function () {    

    // define functions

    function clickAdd() {
        //..
        return "55"
    };

    var that = {};

    // object to return
    that.clickAdd = clickAdd;

    return that;
}

Idea is, I should be able to invoke clickAdd as then ...

page.clickAdd();

but, I get page.clickAdd is not a function.

What are my doing wrong?

Upvotes: 0

Views: 47

Answers (3)

Mike Christensen
Mike Christensen

Reputation: 91656

The issue is that page is function, which returns an object that has a clickAdd property. You'd have to call that function first:

page() // Call page ...
  .clickAdd(); // which returns an object with a clickAdd() function

If you didn't need to keep the page function around anymore, you could also just call the anonymous function and set the return value to page:

page = (function () {    
    return {
       clickAdd: function ()
       {
          return "55";
       }
    };
})();

Now, our anonymous function is called (note the () at the end), which returns an object with a clickAdd function, which is set to the variable page. We can now call:

page.clickAdd();

In essence, page now acts like a static class.

You could also consider making the function a property of an object literal:

var page = {
   clickAdd: function ()
   {
      return "55";
   }
};

page.clickAdd();

Upvotes: 2

Ibu
Ibu

Reputation: 43830

page is a function in your case, so you will have to call it first:

page().clickAdd();

Upvotes: 0

marekful
marekful

Reputation: 15351

You just have to execute the outer function to get its return value stored in page.

page = function () {    

    // define functions

    function clickAdd() {
        //..
        return "55"
    };

    var that = {};

    // object to return
    that.clickAdd = clickAdd;

    return that;
}()

Upvotes: 1

Related Questions