为什么使用命名空间并用“this”污染代码

时间:2013-08-25 21:17:12

标签: javascript closures

我有一个大型JavaScript项目,我正在考虑将其封装在命名空间中以避免全局范围。根据我的阅读,最好不要污染全球范围。在尝试这样做的时候,我看到的代码到处都是“这个”。当我可以确保我的全局变量具有唯一名称时,我为什么要这样做呢?

$m.Timers.Layer = {
    chunk: 3,
    c: null,
    total: null,
    update: function() {
        this.c = 0;
        this.total = $m.db.length;
        setTimeout(this.op1.bind(this), 0);
    },
    op1: function() {
        var end = this.c + this.chunk;
        if (end > this.total) { end = this.total }

        for (this.c; this.c < end; this.c++) {
            alert(this.c);
        }

        if (this.c != this.total) { setTimeout(this.op1.bind(this), 0) }
    }
};

要像'这个'那么难以理解,没有双关语!

编辑:此问题最初使用了Closure这个词,并且已更改为命名空间。

2 个答案:

答案 0 :(得分:2)

在您提供的示例中,使用this的目的是避免在任何地方写$m.Timers.Layer

如果有人通过该属性调用分配给$m.Timers.Layer.update的功能,则在该通话中,this会引用$m.Timers.Layer,因此this.c会引用$m.Timers.Layer.c

也许更重要的是,如果有人这样做:

var l = $m.Timers.Layer;
l.update(/*...*/);

...在通话中,this仍然引用$m.Timers.Layer,因此this.c 仍然指的是$m.Timers.Layer.c


但请注意,闭包 this 彼此之间没什么关系。闭包的目的是关闭定义范围内的数据。 this实际上是函数调用中的参数。实际上,使用闭包避免使用this(通过使用引用所需对象的变量代替)是相当常见的。

进一步阅读(在我的博客上):

答案 1 :(得分:0)

要避免 this ,请沿着

使用闭包
var $m = {Layer:{}};

(function(exports) {

    var c = null;
    var total = null;

    function update() {
        c = 0;
        total = db.length;
        ...
    }

    exports.update = update;
})($m.Layer);
相关问题