H246802 / 30-days-challenge

30天每日打卡
4 stars 0 forks source link

day-21-自定义函数once #21

Open H246802 opened 5 years ago

H246802 commented 5 years ago

写出一个 once 函数,满足以下条件

示例如下

function once(fnParam) {
  // your code
}
let log = once(function() {
  console.log(1)
})

log() // print 1
log() // nothing or undefined
log() // nothing or undefined
log() // nothing or undefined
H246802 commented 5 years ago
function once(fnParam) {
   if(Object.prototype.toString.call(fn) !== "[object Function]"){
    alert('once函数接受的参数必须是一个函数')
    return
  }
  let flag = true
  return function(){
    if(flag){
       flag = false
       fnParam()
    }
    return
  }
}
let log = once(function() {
  console.log(1)
})

log() // print 1
log() // nothing or undefined
log() // nothing or undefined
log() // nothing or undefined