如何将参数传递给Module Pattern

时间:2013-03-31 08:24:43

标签: javascript

我想知道如何将参数传递给模块

例如,我想在调用模块时为计数器传递一个值,类似于

testModule.resetCounter(20);

(来自http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript的代码示例)

var testModule = (function () {

  var counter = 0;

  return {

    incrementCounter: function () {
      return counter++;
    },

    resetCounter: function () {
      console.log( "counter value prior to reset: " + counter );
      counter = 0;
    }
  };

})();

// Usage:

// Increment our counter
testModule.incrementCounter();

// Check the counter value and reset
// Outputs: 1
testModule.resetCounter();

2 个答案:

答案 0 :(得分:2)

只需在resetCounter函数中添加一个参数:

resetCounter: function(count) { ... }

答案 1 :(得分:1)

试试这个:

resetCounter: function (v) {
  console.log( "counter value prior to reset: " + counter );
  counter = (v && (typeof v === "number"))? v: 0;
  console.log( "counter value after reset: " + counter );
}