JavaScript模块的模式-怎么样使用"回报这个"?
-
01-10-2019 - |
题
后做一些读数有关模块的模式,我已经看到一些方法退回的性质,你要是公开的。
一个最常用的方法是宣布你的公共性质和方法内的权利的"返回"的声明,除了你的私人性质和方法。一个类似的方式(在"揭示"模式)提供简单地提到的属性和方法你要是公开的。最后,第三种技术,我看到的是创建一个新的对象在你的模块的功能,为其分配新的特性返回之前说的对象。这是一个有趣的想法,但是需要建立一个新的对象。
所以我在想,为什么不用 this.propertyName
来分配你的公共性质和方法,并且最终使用 return this
在结束了吗?这种方法似乎很简单我说,您可以创建私人的属性和方法与往常一样 var
或 function
语法,或者使用 this.propertyName
语法宣布公的方法。
这里的方法我建议:
(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);
和我们到达 一个已经讨论的模式.为进一步细节,参看达斯丁的文章 界定范围的匿名的功能.
其他提示
我会推荐的风格在哪里你把你的公共性质和方法来一个匿名的目的,然后返回:
var myModule = (function() {
function privateMethod() { ... }
function publicMethod() { ... }
return { publicMethod: publicMethod };
})();
如果你想要发布方法,那么喜欢的东西:
var export = (function() {
var privateMethod = function () {
alert('This is a private method.');
}
var export = {};
export.publicMethod = function () {
alert('This is a public method.');
}
return export;
})();
另一种选择是为了避免的 此 参考。定义功能,创建和返回的一个匿名的对象。
function makeThing(someAttribute) {
var privateVariable = 42;
function someMethod() {
return privateVariable;
}
return {
"publicMethodName": someMethod,
"getAttribute": function() {
return someAttribute;
}
};
}
var thing = makeThing(99);
thing.publicMethodName();
thing.getAttribute();
揭示模块的模式:
var m1 = (function(){ return {method: mthod} })();
var m2 = new function Singleton(){ return {method: mthod} };
var m3 = ({}).prototype = {method: method};
var m4 = ({}).prototype = (function(){ ... })();
var m5 = (function(){}).prototype = {} || (function(){ ... })();
var m6 = (function(extendee){
return extendee.prototype = {attr3: 'attr3'};
})({currentAttr1: 1, currentAttr2: 2});
此外,如果您需要的方法链:
var m = (function(){}).prototype = (function(){
var thus = m; // this
console.log('m this-------', thus);
function fn(){
console.log('fn', thus);
return thus;
}
function f(){
console.log('f', thus);
return 'poop';
}
return {f: f, fn: fn};
})();
console.log('M:', m, 'm.fn', m.fn(), 'm.fn.f', m.fn().f());
还有很多更多的方式,并可以protagonize你的模块。
不隶属于 StackOverflow