-
Notifications
You must be signed in to change notification settings - Fork 1
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
day2 #2
Comments
闭包老题目了 for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i)
}, 1000)
}
// 如何输出 0 1 2
for (var i = 0; i < 3; i++) {
(function (idx) {
setTimeout(function() {
console.log(idx)
}, 1000)
})(i)
} 好说明下为什么,闭包直接的解释是能访问外部变量的函数,但是为什么函数能访问外部变量呢?都是输出i,上面全是3,下面会按序输出? Scope: [AO, globalContext.VO] 自身变量对象找不到后,会去全局作用域找,此时全局作用域的i为3,所以每次都会输出3 Scope: [AO, 匿名函数Context.VO, globalContext.VO] 输出的idx是AO中的形参变量,变量由匿名函数作用域传入,此时匿名函数Context.VO分别有 0,1,2的值。
for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i)
}, 1000)
} var换let就可以了?why Scope: [AO, for循环Context.VO, globalContext.VO] 原理也和上面一样。 |
this指向老题目 var value = 1
var foo = function () {
console.log(this.value)
}
var obj = {
value: 2,
foo,
bar: () => {
console.log(this.value)
}
} 输出 简单来说,js普通函数里的this,是动态的,会根据调用环境有不同指向。 var age = 12
var obj = {
age: 20,
foo: function () {
this.age = 30
return () => {
console.log(this.age)
}
}
}
obj.foo()() // 30 |
节流函数 throttle function throttle(fn, delay) {
var timer
return function () {
var that = this
var args = arguments
timer = setTimeout(() => {
fn.apply(that, args)
timer = null
}, delay)
}
} 在delay时间内,无论触发多少次事件,只会按照间隔执行一次 |
知识点
编程题
算法
The text was updated successfully, but these errors were encountered: