JS面试题笔记3-作用域和闭包

  • 作用域

    全局作用域
    函数作用域
    块级作用域 (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)
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值