verism
verism

Reputation: 1164

How to call a function's methods from within another function

In the form object below, from within the "check" function, how do I call the "show" and "hide" methods of the notification function?

(function (namespace, $, undefined) {
    var form = {
        check : function(){
            form.notification.show(); // Generates an error
        },

        notification : function(){
            this.show = function(){
                ...
            };
            this.hide = function(){
                ...
            };
        }
    };
}(window.namespace = window.namespace || {}, jQuery));

With form.notification.show() I get the following error:

Uncaught TypeError: Cannot read property 'show' of undefined

Upvotes: 0

Views: 56

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328556

Try to define notification outside form and then refer to it:

var notification : { // no function here
        show : function(){...}, // avoid "this"
        hide : function(){...}
};

var form = {
    check : function(){
        notification.show(); // <-- Use here
    },

    notification : notification // and here
};

(I omitted the jQuery protection code for clarity).

The next problem is that you this.show = will assign the function to whatever this is when the function notification() is executed. this isn't notification!

Upvotes: 1

Jay
Jay

Reputation: 1033

You've enclosed it, so you need to return it and that will expose it for you, if you whip the following in chrome console, you'll see you have access to the form object

(function (namespace, $, undefined) {

var form = {

        check : function(){
            form.notification.show(); // Generates an error
        },

        notification : function(){
            this.show = function(){

            };
            this.hide = function(){

            };
        }


};
return{form:form};}(window.namespace = window.namespace || {}, jQuery));

All i've done to your code is added

return{form:form};

After the form object. Hope this helps

EDIT

If you want to only expose certain parts of the form, for example only notifications, you could modify the return like so:

return{form.notification: notification}

Upvotes: 0

Related Questions