简体   繁体   English

JavaScript闭包与全局变量

[英]JavaScript closure vs. global variable

Which is best practice, which results in better performance? 哪种最佳实践可以带来更好的性能?

UPDATE: jsperf.com reports that (a) is faster @ http://jsperf.com/closure-vs-global-variable 更新:jsperf.com报告(a)更快@ http://jsperf.com/closure-vs-global-variable

a) using a closure a)使用闭包

var obj = {
    init: function() {
        var self = this;
        $('#element').click(function() {
            self.clickEvent();
        });
    },
    clickEvent: function() {
        this.miscMethod();
    },
    miscMethod: function() {}
};

b) using the global variable b)使用全局变量

var obj = {
    init: function() {
        // removed self=this closure
        $('#element').click(this.clickEvent); // simple method handler
    },
    clickEvent: function() {
        obj.miscMethod(); // global variable used
    },
    miscMethod: function() {}
};

Both should perform (almost) identically. 两者应(几乎)执行相同的操作。

Best practice is to avoid globals. 最佳做法是避免全局变量。

The problem with your closure code is that it won't work in all cases. 您的关闭代码的问题是,它不能在所有情况下都起作用。 If you do: 如果您这样做:

obj.clickEvent()

then it'll work. 这样就可以了 But if you do: 但是,如果您这样做:

var f = obj.clickEvent;
//hundreds of lines of code
f();

then it won't, as this will not refer to obj on that function call. 则不会,因为this不会在该函数调用上引用obj If you just immediately pass obj off to something that doesn't use it in a strange way, though, then you won't have that problem, so it's 'cleaner'... but I still think it's too easy to make mistakes, so I recommend the global variable approach. 但是,如果您只是立即将obj传递给没有以奇怪的方式使用它的东西,那么您就不会有问题,所以它是“干净的” ...但是我仍然认为犯错误太容易了,因此,我建议使用全局变量方法。

Nice write up about closures here. 很高兴在这里写有关闭包的内容。

JavaScript Closures - MDC JavaScript闭包-MDC

In most browsers, there is no significant performance difference; 在大多数浏览器中,性能没有显着差异。 however, Chrome seems to suffer a 75% slowdown using this (correct my quick performance test if I am mistaken). 但是,使用this ,Chrome似乎会出现75%的速度下降 (如果我输入错误,请更正我的快速性能测试)。 Probably the main best practice issue is that it can sometimes be unclear which object this refers to. 可能是主要的最佳做法的问题是,它有时是不清楚哪个对象this指的是。

As for declaring (or using without declaring) your own global variables, we call it global namespace "pollution" if we use too many of them. 至于声明(或使用而不声明) 自己的全局变量,如果我们使用过多全局变量,我们将其称为“全局命名空间”。 This can lead to different parts of JavaScript code interfering with one another, which good encapsulation using closures or "namespacing" avoids. 这可能导致JavaScript代码的不同部分相互干扰,避免使用闭包或“命名空间”进行良好的封装。 The best practice is to only use at most one or two global variables. 最佳做法是仅使用一个或两个全局变量。 For example, jQuery uses just two: jQuery and $ (the latter can be turned off if it conflicts with another library). 例如,jQuery仅使用两个: jQuery$ (如果与另一个库冲突,则可以关闭后者)。

1) Since globals are dangerous, consider putting global variable names in all caps so that they're obvious to anyone (including you) who is reading the code. 1)由于全局变量很危险,请考虑将全局变量名称放在所有大写形式中 ,以使任何正在阅读代码的人(包括您)都可以看到它们。

2) your first snippet isn't valid. 2)您的第一个代码段无效。

function obj = {
     // your object stuff
}

should be 应该

var obj = {
    // your object stuff
}

Additionaly, that's not actually a closure. 另外,这实际上不是关闭。 Here is how you implement a singleton in Javascript. 这是在Java中实现单例的方式。

var mySingleton = (function () {
    var privateVar = "foo";

    function privateFunction() { //this function can only be accessed by other private 
                                 //and privaleged functions defined in this closure
        // do stuff.
    }

    //stuff to run immediately that will also have access to private variables/functions

    singletonObj = {
         key1:"value1",
         key2:"value2",
         privilgedFunction: function () { // this method is accessible from the outside
             // do stuff. you can access private variables in here
         }
    };

    return singletonObj; //return the object that you just created
}()); //immediately execute the function, returning an object with private variables

I'm assigning the result of a function that I immediately execute to a variable. 我将立即执行的函数的结果分配给变量。 That function returns an object, therefore, I am assigning an object to that variable. 该函数返回一个对象,因此,我将一个对象分配给该变量。 BUT that object also has private members and private functions. 但是该对象也具有私有成员和私有功能。

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

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