简体   繁体   English

这两种JavaScript模式之间的优缺点是什么?

[英]What are the Advantages and Disadvantages Between These Two JavaScript Patterns?

These two JavaScript patterns are very similar. 这两种JavaScript模式非常相似。 I would like to know which one is better and why and how either one can be improved. 我想知道哪种更好,为什么以及如何改进。

First Approach: 第一种方法:

"MODULE" in window || (window.MODULE = {} );

MODULE.utils = (function ($) {

    var utils = {};

    //public
    utils.todo = function() {
        //#
    }

    //private
    function init() {
        //#
    }

    init();

    return utils;
}(jQuery));

Second Approach : 第二种方法

"MODULE" in window || (window.MODULE = {} );

MODULE.utils = (function() {

    function todo(){
        //#
    }

    function init() {
        //#
    }

    return {
        init:init
    }

})();


$(function() {
    MODULE.utils.init();
});

Both of your options don't really have much in the way of pros or cons, it's more just about personal preference. 您的两种选择实际上并没有太多利弊,而更多是关于个人喜好。 Both could be adjusted to provide scope a bit better. 两者都可以调整以提供更好的范围。

I have my own preference, it relies on Underscore . 我有自己的偏好,它依赖于Underscore It doesn't really promote private variables or functions but I rarely find this an issue. 它并没有真正促进私有变量或函数,但是我很少发现这个问题。 If you want to introduce jQuery, etc, it would be best to wrap in an anonymous function to $ is actually jQuery (or an interchangeable library). 如果要引入jQuery等,最好将匿名函数包装为$实际上是jQuery (或可互换库)。

As you'll see below, my preference requires a little more code to get you going (although some of it's not necessary), but having tried a few variations of what you originally proposed, I've found that my solutions lends itself to more understandable code and it's easier for other devs to get the grasp of what's going on, especially if they've got experience with Backbone.View . 正如您将在下面看到的那样,我的偏好设置需要更多代码才能入门(尽管其中一些不是必需的),但是尝试了您最初提出的一些变体之后,我发现我的解决方案可为您提供更多帮助易于理解的代码,其他开发人员更容易掌握发生的情况,特别是如果他们有Backbone.View经验。

EDIT: Wrapped in an anonymous function to demonstrate integrating jQuery and protected scope. 编辑:包裹在一个匿名函数中,以演示集成jQuery和受保护的范围。

var MyNamespace = MyNamespace || {};

(function($, MyNamespace) {

    MyNamespace.MyModule = function(options) {
        this.defaults = this.defaults || {};
        // have had trouble with _.defaults so _.extend instead
        this.options = _.extend({}, this.defaults, options);
        this.initialize.call(this);
        // define private stuff in here if you want
    };

    _.extend(MyNamespace.MyModule.prototype, {

        defaults: {
            myOption: "test"
        },

        initialize: function()
        {
            // ensure this always refers to our MyModule instance
            _.bindAll(this);
            this.$el = $("#some-widget");
            // Look Ma! log is already binded to this!
            this.$el.on("click", this.log);
        },

        setMyOption: function(value)
        {
            this.options.myOption = value;
        },

        log: function()
        {
            console.log("myOption: ", this.options.myOption);
        }

    });

})(jQuery, MyNamespace) 

var myModule = new MyNamespace.MyModule({ myOption: "Hey SO!" });
myModule.log(); // -> myOption: Hey SO!
myModule.setMyOption("Setter");
myModule.log(); // -> myOption: Setter
 "MODULE" in window || (window.MODULE = {} ); 

Why do that? 为什么这样 We're already in the global scope here, right, so we can just do: 我们已经在全球范围内了,所以我们可以这样做:

var MODULE = MODULE || {};

Other that that, the only real difference (other than style) is in the first example init is called immediately from within the "module," while in the second example you call init manually at some later point in time (even if it's immediately after the module loads in this case). 其他的是的是,唯一真正的区别(除了款式以外)是在第一个例子中init从内立即被称为“模块”,而你拨打第二个例子init手动在以后的某个时间点(即使它后立即在这种情况下,模块会加载)。 So, if you need to delay the call to init , the second is preferable; 因此,如果需要延迟对init的调用,则最好使用第二个方法; if you want it to happen immediately, the first is preferable (aside from preferences about style). 如果您希望它立即发生,则首选第一个(除了对样式的偏好)。

The second approach assumes the variable named $ is a function that accepts a single argument that is also a function — probably an assumption that $ == jQuery . 第二种方法假定名为$的变量是一个函数,该函数接受一个也是函数的参数-可能假定$ == jQuery This may not always be true. 这可能并不总是正确的。 In the first approach, you guarantee that $ == jQuery within the scope of your module because you pass it in as an argument to the anonymous function that initializes your module. 在第一种方法中,您保证$ == jQuery在模块范围内,因为您将它作为参数传递给初始化模块的匿名函数。

Beyond that, there's not a lot of difference between the two. 除此之外,两者之间没有太大区别。 I prefer the second approach for exposing public methods so that my syntax looks the same for both public and private methods, and so that I have to explicitly specify which methods are public. 我更喜欢使用第二种方法公开公共方法,以便我的语法在公共方法和私有方法中看起来都一样,因此我必须明确指定哪些方法是公共的。 But that's just stylistic. 但这只是风格。

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

相关问题 iPhone:使用CSS / JavaScript开发的优点和缺点是什么? - iPhone: What are the Advantages and Disadvantages of Developing with CSS/Javascript? JQuery和Glow JavaScript库的优点和缺点是什么? - What are the Advantages and Disadvantages of JQuery and Glow JavaScript Libraries? 这两种JavaScript模式之间有什么区别 - What's the difference between these two JavaScript patterns 使用Javascript生成的网站的优点/缺点 - Advantages / Disadvantages to websites generated with Javascript 在Javascript中调用函数时使用“()”的优点和缺点? - Advantages and disadvantages of using “()” while calling function in Javascript? 结合使用jQuery UI和AngularJS的优缺点是什么? - What are the advantages and disadvantages of using Jquery UI with AngularJS? 与官方标准相比,将JSON数据作为text / javascript提供的优点和缺点是什么:application / json? - What are the advantages and disadvantages of serving JSON data as text/javascript compared to the official standard: application/json? 提取两个模式之间的数字javascript - Extract numbers between two patterns javascript 这两种JavaScript模式之间有什么区别吗? - Is there any difference between this two JavaScript patterns? 这两种构造器模式有什么区别? - What is the difference between these two constructor patterns?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM