作用域和闭包 - 解答
this 的不同应用场景
- 作为普通函数调用
- 使用
callapplybind - 作为对象方法调用
- 在 class 的方法中调用
- 箭头函数
创建 10 个<a>标签,点击的时候弹出来对应的序号
js
// 创建 10 个`<a>`标签,点击的时候弹出来对应的序号
let i, a
for (i = 0; i < 10; i++) {
a = document.createElement('a')
a.innerHTML = i + '<br>'
a.addEventListener('click', function (e) {
e.preventDefault()
alert(i)
})
document.body.appendChild(a)
}怎么解决?—— 把 let 移动到 for 里即可
实际开发中闭包的应用
参考之前的示例。再次强调闭包中自由变量的寻找方式!!!
js
// 隐藏数据,只提供 API
function createCache() {
let data = {} // 闭包中的数据,被隐藏,不被外界访问
return {
set: function (key, val) {
data[key] = val
},
get: function (key) {
return data[key]
}
}
}
let c = createCache()
c.set('a', 100)
console.log( c.get('a') )手写 bind 函数
先回顾 bind 函数的应用
js
function fn1(a, b) {
console.log('this', this)
console.log(a, b)
}
const fn2 = fn1.bind({ x: 100 }, 10, 20) // bind 返回一个函数,并会绑定上 this
fn2()手写 bind
js
Function.prototype.bind1 = function () {
// 将参数解析为数组
const args = Array.prototype.slice.call(arguments)
// 获取 this(取出数组第一项,数组剩余的就是传递的参数)
const t = args.shift()
const self = this // 当前函数
// 返回一个函数
return function () {
// 执行原函数,并返回结果
return self.apply(t, args)
}
}
讨论区
欢迎留下想法与补充