JavaScript模块模式 - 使用"return this"怎么样?

Rob*_*ons 14 javascript design-patterns module-pattern

在做了一些关于模块模式的阅读之后,我已经看到了几种返回你想要公开的属性的方法.

最常见的方法之一是在"return"语句中声明您的公共属性和方法,除了您的私有属性和方法.类似的方式("Revealing"模式)是简​​单地引用您想要公开的属性和方法.最后,我看到的第三种技术是在模块函数中创建一个新对象,在返回所述对象之前为其分配新属性.这是一个有趣的想法,但需要创建一个新对象.

所以我在想,为什么不只是this.propertyName用来分配你的公共属性和方法,最后用到return this最后?这种方式对我来说似乎更简单,因为您可以使用通常varfunction语法创建私有属性和方法,或使用this.propertyName语法来声明您的公共方法.

这是我建议的方法:

(function() {

var privateMethod = function () {
    alert('This is a private method.');
}

this.publicMethod = function () {
    alert('This is a public method.');
}

return this;

})();
Run Code Online (Sandbox Code Playgroud)

使用上述方法有任何优点/缺点吗?其他人怎么样?

Tör*_*bor 30

您的函数没有对象上下文,因此在这种情况下this引用全局window对象.您指定的每个属性都会this自动污染全局命名空间.

(function() {
    console.log(this == window); // true

    this.publicMethod = function () {
        alert('This is a public method.');
    }

})();

console.log(publicMethod); // function()
Run Code Online (Sandbox Code Playgroud)

您可以显式传递一个对象来告诉使用哪个上下文.

var MYAPP = {};

(function() {
    // 'this' will now refer to 'MYAPP'
    this.publicMethod = function () {
        alert('This is a public method.');
    }
}).call(MYAPP);

console.log(publicMethod); // undefined
console.log(MYAPP.publichMethod); // function()
Run Code Online (Sandbox Code Playgroud)

你可以用其他风格写一下:

var MYAPP = (function(my) {
    var my;
    ?
    return my;
})(MYAPP);
Run Code Online (Sandbox Code Playgroud)

我们到达了一个已经讨论过的模式.有关详细信息,请参阅Dustin关于范围匿名函数的文章.