简体   繁体   English

如何从另一个函数中调用函数的方法

[英]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? 在下面的form对象中,如何从“检查”功能中调用通知功能的“显示”和“隐藏”方法?

(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: 使用form.notification.show()我得到以下错误:

Uncaught TypeError: Cannot read property 'show' of undefined 未捕获的TypeError:无法读取未定义的属性“ show”

Try to define notification outside form and then refer to it: 尝试在form之外定义notification ,然后引用它:

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). (为了清楚起见,我省略了jQuery保护代码)。

The next problem is that you this.show = will assign the function to whatever this is when the function notification() is executed. 接下来的问题是,你this.show =将分配功能,无论this功能时notification()被执行。 this isn't notification ! this不是notification

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 您已经将其封闭起来,因此需要将其退还给您,这将为您公开,如果您在chrome控制台中鞭打了以下内容,您将看到可以访问form对象

(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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM