-
作用域
全局作用域
函数作用域
块级作用域 (ES6 新增) -
自由变量
一个变量在当前作用域没有定义,但被使用了
向上级作用域,一层一层依次寻找,直到找到为止
如果全局作用域都没找到,则报错 not defined -
闭包
作用域应用的特殊情况,有两种表现:
- 函数作为参数被传递
// 函数作为参数被传递 function print(fun) { let b = 200 fun() } const b = 100 function fun() { console.log(b) } print(fun) // 100
- 函数作为返回值被返回
// 函数作为返回值 function create() { const a = 100 return function () { console.log(a) } } const fn = create() const a = 200 fn() // 100
- 闭包:所有自由变量的查找,是在函数定义的地方向上级作用域查找。而非在执行的地方
-
Q1:this 的不同应用场景,如何取值
this 取值是在函数执行时候决定而非函数定义时
- 作为普通函数 – window
- 使用 call apply bind – 指定 this 指向
- 作为对象方法被调用 – 对象本身
- 在 class 方法中调用 – 返回实例
- 箭头函数 – 上一级作用域 this
-
Q2:手写 bind 函数
// 模拟 bind Function.prototype.bind1 = function () { // 将参数拆解为数组 const args = Array.prototype.slice.call(arguments) // 获取 this (数组第一项) const t = args.shift() // fn1.bind(...) 中的 fn1 const self = this // 返回一个函数 return function () { return self.apply(t, args) } } function fn1(a, b) { console.log('this', this) console.log(a, b) return 'this is fn1' } const fn2 = fn1.bind1({ x: 100 }, 10, 20) const res = fn2() console.log(res)
-
Q3:实际开发中闭包的应用场景,举例说明
隐藏数据
// 闭包隐藏数据 只提供 API function createCache() { const data = {} // 闭包中的数据,被隐藏,不被外界访问 return { set: function (key, val) { data[key] = val }, get: function (key) { return data[key] }, } } const c = createCache() c.set('a', 100) console.log(c.get('a'))
-
Q4:创建 10 个 a 标签,点击弹出对应序号
let a for (let 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) }
JS面试题笔记3-作用域和闭包
最新推荐文章于 2024-01-18 16:14:13 发布