Javascript 转换为命名空间并调用函数

发布于 2024-11-29 00:46:54 字数 411 浏览 0 评论 0 原文

我是一个典型的 Web 开发人员,在 JS 中使用全局的一切。我现在已经看到曙光并希望转换为命名空间。因此,在我当前的项目中,我有一个页面,该页面具有三个 JS 函数(当前均为全局函数),在调用时将文本分配给锚点并附加单击方法来切换特定 div 的可见性。非常标准。

因此,示例函数写为:

function toggleComments(){
   $("comments-section").hide();
   $("comments-button").click(function (){
      blah
      return false;
   });
}

我的问题是如何创建一个命名空间来保存这些函数然后调用它们?

我发现了不同的例子,但没有结论性的。

任何帮助都会很棒。

I'm a typical web dev that's used global for everything in JS. I've now seen the light and want to convert to namespaces. So on my current project I have a page that has three JS functions (all global currently) that when called assign text to anchors and attach click methods to toggle the visibility of particular divs. Very standard.

So an example function is written as:

function toggleComments(){
   $("comments-section").hide();
   $("comments-button").click(function (){
      blah
      return false;
   });
}

My question is how do I create a namespace to hold these functions and then call them?

I've found varying examples but nothing conclusive.

Any help would be great.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗笺 2024-12-06 00:46:54

billy Moon 显示了一个良好的开端,但使用对象文字的问题是您无法交叉引用其他字段/函数/属性。

我更喜欢揭示模块模式(参见 http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

揭示模块模式结合了自执行函数、闭包的利用(某种程度)来提供内部私有函数/字段,并允许您传递参数来初始化命名空间对象。

var namespacedObject = function(param) {

    var settings = param || someDefaultSetting, //default if no param supplied
        somePrivateField = "someValue",
        somePublicField = "i'm public";

    //define some method we will later make public
    function toggleComments(){
        $("comments-section").hide();
        $("comments-button").click(function (){
             $(this).value= somePrivateField;
             return false;
        });
    }

    //this is where the magic happens, 
    //return object with all public fields/functions
    return { 
        toggleComments : toggleComments,
        somePublicField : somePublicField
    };

}(someParam);

您可以看到命名空间对象包含一个私有字段 somePrivateField,可以从公共访问方法中引用该字段。另外,请注意,我已经公开了一个公共字段,并接受了一些我可以在函数等中使用/引用的参数(如果没有传入任何内容,您可以将其默认为某些默认值。

可以像这样使用:

namespacedObject.toggleComments();
alert(namespacedObject.somePublicField);
alert(namespacedObject.somePrivateField); //undefined - it's private of course!

我喜欢这个的原因之一是只需浏览自执行函数返回的对象文字,就可以很容易地看出什么是公共/私有

希望这有帮助

billy moon shows a good start, but the problem with using object literals, is that you cannot cross reference other fields/functions/properties.

I much prefer the revealing module pattern (see http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/)

the revealing module pattern combines a self-executing function, an exploitation (of sorts) of closures to provide internal private functions/fields, and allows you to pass params to initialise your namespaced object.

var namespacedObject = function(param) {

    var settings = param || someDefaultSetting, //default if no param supplied
        somePrivateField = "someValue",
        somePublicField = "i'm public";

    //define some method we will later make public
    function toggleComments(){
        $("comments-section").hide();
        $("comments-button").click(function (){
             $(this).value= somePrivateField;
             return false;
        });
    }

    //this is where the magic happens, 
    //return object with all public fields/functions
    return { 
        toggleComments : toggleComments,
        somePublicField : somePublicField
    };

}(someParam);

You can see that the namespaced object contains a private field somePrivateField, which can be referenced from publicly accessible methods. Also, notice i have exposed a public field, and accepted some params which i may use/reference in functions etc (and you can default it to some default if nothing is passed in.

can be used like this:

namespacedObject.toggleComments();
alert(namespacedObject.somePublicField);
alert(namespacedObject.somePrivateField); //undefined - it's private of course!

one reason i like this is that it's very easy to see what is public/private by just glancing at the object literal returned from the self-executing function

Hope that's helpful

还如梦归 2024-12-06 00:46:54
// choos a namespace name that will not conflict with existing global variables
var myNS = {
        toggleComments: function(){
            $("comments-section").hide();
            $("comments-button").click(function (){
                // blah
                return false;
            });
        },
        anotherFunc: function(){
            return "something";
        }
}

// called like this
myNS.toggleComments();
alert( myNS.anotherFunc() );

此外,您应该尝试将代码包含在匿名自调用函数中。这意味着您可以在全局命名空间中没有任何内容,因此没有污染的风险。

// other peoples/modules code
var myVariable = "whatever";

// anonymous function for your self contained code
(function(){
var myVariable = "inside anonymous function";
alert(myVariable);
})() // the empty brackets envoke the anonymous function

// still retains value from before your self envoking anonymous function
alert(myVariable);
// choos a namespace name that will not conflict with existing global variables
var myNS = {
        toggleComments: function(){
            $("comments-section").hide();
            $("comments-button").click(function (){
                // blah
                return false;
            });
        },
        anotherFunc: function(){
            return "something";
        }
}

// called like this
myNS.toggleComments();
alert( myNS.anotherFunc() );

Additionally, you should try to contain your code in an anonymous self invoking function. This means you can have nothing in the global namespace, therefore no risk of pollution.

// other peoples/modules code
var myVariable = "whatever";

// anonymous function for your self contained code
(function(){
var myVariable = "inside anonymous function";
alert(myVariable);
})() // the empty brackets envoke the anonymous function

// still retains value from before your self envoking anonymous function
alert(myVariable);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文