定时器
function await(message) {
setTimeout(function timer() {
console.log(message)
}, 1000);
}
await('hello world')
timer 函数里面对变量 message 引用, timer 具有涵盖 await() 作用域的闭包,
事件
function setupBot(name, selector) {
document.querySelector(selector).click = function () {
console.log(name)
}
}
setupBot('点击', '#app')
循环
for (var i = 0; i < 5; i++) {
(function (j) {
setTimeout(() => {
console.log(j)
}, 1000);
})(i)
}
let 声明有一个特殊的行为,这个行为指出变量在循环过程中不止被声明一次,每次迭代都会声明,随后每次迭代都会使用上一个迭代结束时的值来初始化这个变量。
for (let i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i)
}, 1000);
}
模块
function CoolMode() {
let something = 'cool'
let another = [1, 2, 3]
function doSomething() {
console.log(something)
}
function doAnother() {
console.log(another)
}
return {
doSomething,
doAnother
}
}
let foo = CoolMode()
foo.doSomething()
foo.doAnother()
单例模式
let foo = (function CoolMode() {
let something = 'cool'
let another = [1, 2, 3]
function doSomething() {
console.log(something)
}
function doAnother() {
console.log(another)
}
return {
doSomething,
doAnother
}
})()
foo.doSomething()
foo.doAnother()
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!