在阅读了一些有关模块模式的内容后,我看到了几种返回您想要公开的属性的方法。
除了私有(private)属性和方法之外,最常见的方法之一是在“return”语句中声明您的公共(public)属性和方法。一种类似的方式(“揭示”模式)是提供对您希望公开的属性和方法的简单引用。最后,我看到的第三种技术是在模块函数内创建一个新对象,在返回所述对象之前将新属性分配给该对象。这是一个有趣的想法,但需要创建一个新对象。
所以我在想,为什么不直接使用this.propertyName
来分配你的公共(public)属性和方法,最后使用return this
呢?这种方式对我来说似乎更简单,因为您可以使用通常的 var
或 function
语法创建私有(private)属性和方法,或者使用 this.propertyName
声明公共(public)方法的语法。
这是我建议的方法:
(function() {
var privateMethod = function () {
alert('This is a private method.');
}
this.publicMethod = function () {
alert('This is a public method.');
}
return this;
})();
使用上述方法有什么优点/缺点吗?其他人呢?
最佳答案
您的函数没有对象上下文,因此在这种情况下 this
引用全局 window
对象。您分配给 this
的每个属性都会自动污染全局命名空间。
(function() {
console.log(this == window); // true
this.publicMethod = function () {
alert('This is a public method.');
}
})();
console.log(publicMethod); // function()
你可以显式地传递一个对象来告诉它使用哪个上下文。
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()
你可以用其他风格来写:
var MYAPP = (function(my) {
var my;
⋮
return my;
})(MYAPP);
我们到达了an already discussed pattern .有关详细信息,请参阅 Dustin 关于 Scoping anonymous functions 的文章.
关于JavaScript 模块模式 - 使用 "return this"怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713431/