nodejs once 模块

module once   模块主要功能是为了使得回调只会执行一次 非常适合于只需要执行一次的函数
  var wrappy = require('wrappy')
module.exports = wrappy(once)
//执行一次后 在函数的原型上定义一个once 方法,
once.proto = once(function () {
  Object.defineProperty(Function.prototype, 'once', {
    value: function () {
      return once(this)
    },
    configurable: true
  })
})

function once (fn) {
  var f = function () {
//  再次运行的话 返回 cb上一次的返回值。
    if (f.called) return f.value
    f.called = true
    return f.value = fn.apply(this, arguments)
  }
  f.called = false
  return f
}

猜你喜欢

转载自317948915.iteye.com/blog/2344260