从另一个js文件中的javascript函数调用命名空间函数时出现问题 [英] problem calling namespaced function from javascript function in another js file

查看:47
本文介绍了从另一个js文件中的javascript函数调用命名空间函数时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Namespacing对我来说是js中的新事物-我的项目已经变得非常复杂,现在该驯服野兽了:-P

Namespacing is new to me in js - and my project has grown very complex so it's time to tame the beast :-P

我已经使用模块模式在foo.js中创建了名称空间foo.

I have created a namespace foo in foo.js using the module pattern.

var foo = (function () {       
        update: function () {
            alert('z');
        }
    };
}());

我可以使用$(function () {foo.update(); });

但是我似乎无法触发它从另一个js文件中调用.

But I can't seem to get it to fire calling from another js file.

我正在尝试从bar.js调用它

I am trying to call it from bar.js

function updateTheFoo() {
    foo.update();
}

实际用例要复杂得多,因为我正在动态创建的jQueryUI对话框中使用它,而可变按钮是动态传递代码的-但这很容易...

The actual use case is much more complicated, as I'm using it within a dynamically created jQueryUI dialog with variable buttons that are passed code on the fly - but that's the easy part...

我确定这很简单-但我似乎找不到答案.

I'm sure this is something simple - but I can't seem to find the answer.

非常感谢!

推荐答案

您的函数应编写如下:

var foo = (function () {       
    return {
        update: function () {
            alert('z');
        }
    };
}());

正如马特(Matt)所说,您的问题是缺少返回声明.您正在使用的是一个模块模式,该模式比命名空间更进一步,该模式允许在命名空间中同时具有名称空间和私有变量/函数,并仅通过return语句公开您想要的内容.
您可以在 YUI博客上的这篇文章中了解有关模块模式的更多信息.

your problem as Matt says is the missing return statement. What you are using there is a module pattern which is one step further to namespacing that allows to both have a namespace and private variables/functions inside that namespace and only expose what you want with the return statement.
You can read more about the module pattern in this article on the YUI blog.

这篇关于从另一个js文件中的javascript函数调用命名空间函数时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆