1

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

例如,我想在调用模块时为 counter 传递一个值,smt like

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();
4

2 回答 2

2

只需向您的resetCounter函数添加一个参数:

resetCounter: function(count) { ... }
于 2013-03-31T08:26:31.197 回答
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 );
}
于 2013-03-31T08:29:45.150 回答