Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
H246802 opened this issue Dec 18, 2018 · 1 comment
Open

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

H246802 opened this issue Dec 18, 2018 · 1 comment

Comments

@H246802
Copy link
Owner

H246802 commented Dec 18, 2018

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

  • once 函数只接受一个参数 fnParam,这个参数必须是一个函数
  • once 函数返回一个函数 fnResult
  • 如果调用一次 fnResult,则执行一次 fnParam
  • 如果调用多次 fnResult,也只会执行一次 fnParam

示例如下

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
Copy link
Owner Author

H246802 commented Dec 18, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant