本文介绍了JavaScript:模块模式差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var module = (function(){
    return {}
})()

(function(context){
    var module = {}
    context.module = module;
})(this)


推荐答案

不等于变量。在全局范围(即这个引用窗口中),它们是类似的。然而,例如,当您尝试他们:

A property of this is not equivalent to a variable. In the global scope (i.e. where this references window), they are similiar. Yet, for example they will have a different behavior when you try to delete them:

> this.module = {};
> delete this.module
true
> var module = {};
// cant be deleted

除此之外,两个代码片段都创建一个空对象,在一个闭包中,您可以定义本地(私有)变量/函数等。在第二个函数中,对象也被分配给局部变量 module ,但可以在第一个。

Apart from that, both snippets create an empty object, wrapped inside a closure where you could define local (private) variables/functions etc. In your second function the object is also assigned to the local variable module, but that could be done in the first one as well.

@Eric:您的方法,使用,第一个关于变量。但是,它将创建一个匿名函数的实例,而不是返回一个普通对象。它将继承自定义原型的属性,所以例如 module.constructor 然后将指向匿名函数(不能被垃圾回收,但是甚至重用以创建一个克隆)。我不建议使用这个。

@Eric: Your approach, using the new operator, is similiar to the first one regarding the variable. However, it will create an instance of that anonymous function instead of returning a plain object. It will inherit properties from a custom prototype, so for example module.constructor will then point to the anonymous function (which cannot be garbage collected, but e.g. even reused to create a clone). I would not recommend to use this.

这篇关于JavaScript:模块模式差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:10