http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
我正在阅读上面的大师作品。我仍然无法从上面的文章中得到两件事。
var myRevealingModule = (function () {
var privateVar = "Ben Cherry",
publicVar = "Hey there!";
function privateFunction() {
console.log( "Name:" + privateVar );
}
function publicSetName( strName ) {
privateVar = strName;
}
function publicGetName() {
privateFunction();
}
// Reveal public pointers to
// private functions and properties
return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};
})();
myRevealingModule.setName( "Paul Kinlan" );
相关问题: JavaScript design pattern: difference between module pattern and revealing module pattern?
我从上述问题中了解了很多部分。任何人都可以将上述revealing module pattern
转换为传统的module pattern
,以便我可以看到差异。
答案 0 :(得分:0)
模块模式代码如下所示:您可以看到jsfiddle
var myModule = (function () {
var privateVar = "Ben Cherry";
function privateFunction() {
console.log( "Name:" + privateVar );
}
return {
setName: function( strName ) {
privateVar = strName;
},
greeting: "Hey there!",
getName: function() {
privateFunction();
}
};
})();
myModule.setName( "Paul Kinlan" );
答案 1 :(得分:0)
避免显示模块模式时有两个选项。您可以使用对象文字或存根返回对象。
使用对象文字:
var myRevealingModule = (function () {
var privateVar = "Ben Cherry";
function privateFunction() {
console.log( "Name:" + privateVar );
}
return {
setName: function( strName){
privateVar = strName;
},
greeting: "Hey there!",
getName: function() {
privateFunction();
}
};
})();
使用存根:
var myRevealingModule = (function () {
var privateVar = "Ben Cherry";
function privateFunction() {
console.log( "Name:" + privateVar );
}
var stub = {};
stub.greeting = "Hey there!";
stub.setName = function ( strName ) {
privateVar = strName;
};
stub.getName = function () {
privateFunction();
}
return stub;
})();
关键是除非你打算隐藏它,否则不要在封闭中放任何东西。不要在封口中放一些东西,然后再“揭示”它。