-
Notifications
You must be signed in to change notification settings - Fork 67
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
惰性函数 #12
Comments
因为上面第三行的时候,把foo函数重写了,所以未来只会有 “嘻嘻,我出现了哦” |
试了下,这样就不行。 var foo = function() {
console.log('你会发现我只出现一次哦,不管你调用几次')
var foo = function() {
console.log('嘻嘻,我出现了哦')
}
foo()
}
foo()
foo() 😢 |
这是因为你在第三行的时候,重新var了一下foo(新foo),这个新foo的作用域是在范围比较大的foo(旧foo)里面,所以不能把旧foo进行重新赋值为一个新foo,这样每次运行的时候,都是存在两个不同的foo |
@xiaohesong 三克油,这些都是你自己翻译的吗? |
@YuYuBei 嗯,看到一些不错的会记录下来 |
class Man {
constructor(name) {
this.name = name
console.log(`Hi! This is ${name}`)
this.queue = []
setTimeout(() => {
this.next()
}, 0)
}
toQueue(fn, isFirst) {
if(isFirst) {
this.queue.unshift(fn)
} else {
this.queue.push(fn)
}
return this
}
next() {
const fn = this.queue.shift()
fn && fn()
}
eat(food) {
const eater = () => {
console.log(`Eat ${food}`)
this.next()
}
this.toQueue(eater)
return this
}
sleepFirst(time) {
this.sleep(time, true)
}
sleep(time, isFirst) {
const sleeper = () => {
setTimeout(() => {
console.log(`Wake up after ${time}`)
this.next()
}, time * 1000)
}
this.toQueue(sleeper, isFirst)
return this
}
}
const LazyMan = (name) => new Man(name)
LazyMan('小明').eat('午餐').sleep(2).eat('晚餐').sleepFirst(3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
今天看到一篇文章中有提到 惰性函数 。感觉很新奇,去查了下,发现就是自己调用自己。
可以让你只在第一次的时候调用你需要处理的函数,后面可以直接使用函数。
还挺有意思的,留下个问题,你觉得这个是因为啥,为啥会出现上面的情况?
The text was updated successfully, but these errors were encountered: