- 当函数可以记住并访问所在的词法作用域时,就产生了闭包,即使函数是在当前词法作用域之外执行的。
- 闭包是指有权访问另一个函数作用域中变量的函数
function foo(a) {
setTimeout(function timer(){
console.log(a)
}, 1000)
}
foo(2);
for(var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
for (var i = 0; i < 5; i++) {
(function x(n) {
setTimeout(() => {
return console.log(n);
}, n * 1000);
})(i)
}
// let throttleLastFireTimes = []
// function throttle(delay = 500, func) {
// return (function (index) {
// return function () {
// let now = Date.now()
// if (!throttleLastFireTimes[index] || (now - throttleLastFireTimes[index] > delay)) {
// throttleLastFireTimes[index] = now
// func && func()
// }
// }
// })(throttleLastFireTimes.length)
// }
// let throttleRender = throttle(500, render)
let memorizedData = []
var index
function useState(initValue) {
index++
let val = memorizedData[index] || initValue
let setVal = (newVal) => {
memorizedData[index] = newVal
// throttleRender()
render()
}
return [val, setVal]
}
function render() {
index = 0
const [age, setAge] = useState(18)
const [price, setPrice] = useState(100)
console.log(`age: ${age}, price: ${price}`);
setTimeout(() => {
setAge(age + 1)
setPrice(price + 1)
}, 1000);
}
render()
let memorizedData = []
var index
function useState(initValue) {
index++
let val = memorizedData[index] || initValue
let setVal = (newVal) => {
memorizedData[index] = newVal
render()
}
return [val, setVal]
}
function render() {
let age = 18
useEffect(() => {
console.log(`age: ${age}`);
}, [age])
}
render()