前端面试题4--JS基础--作用域和闭包

87 阅读2分钟

作用域

  • 全局作用域
  • 函数作用域
  • 块级作用域

自由变量

  • 一个变量在当前作用域没有定义,但被使用了
  • 向上级作用域,一层一层依次寻找,直至找到为止
  • 如果到全局作用域都没有找到,则报错 xx is not defined

闭包

作用域应用的特殊情况,有两种表现:

  • 函数作为参数被传递
  • 函数作为返回值被返回

所有自由变量的查找,是在函数定义的地方,向上级作用域查找,不是在执行的地方!!!

// 函数作为返回值
function create () {
    let a = 100
    return function () {
        console.log(a)
    }
}
let fn = create()
let a = 200
fn()   // 100
// 函数作为参数
function print (fn) {
    let a = 200
    fn()
}
let a = 100
function fn () {
    console.log(a)
}
print(fn)  // 100

this

this 的不同应用场景及取值:

  • 作为普通函数被调用(返回window)
  • 使用 call apply bind 调用(传入什么就返回什么)
  • 作为对象方法被调用(返回当前对象本身)
  • 在 class 方法中调用(返回当前实例本身)
  • 箭头函数(永远找上级作用域的this)

this 在各个场景中取什么值,是在函数执行时确定,不是在定义时!!!

/* 作为普通函数调用 */
function fn1 () {
    console.log(this)
}
fn1() // window

/* 使用 call apply bind 调用 */
fn1.call({x: 100}) // {x: 100}
const fn2 = fn1.bind({x: 200}) // bind会返回新函数去执行
fn2() // {x: 200}
/* 作为对象方法被调用,返回当前对象 */
const zhangsan = {
    name: '张三',
    sayHi () {
        console.log(this) // this 即当前对象
    },
    wait () {
        setTimeout(function () { // 作为普通函数被执行
            console.log(this) // this === window
        })
    },
    waitAgain () {
        /* 箭头函数永远取上级作用域的this */
        setTimeout(() => {
            console.log(this) // this 即当前对象
        })
    }
}
class People {
    constructor (name) {
        this.name = name
        this.age = 20
    }
    sayHi () {
        console.log(this)
    }
}
const zhangsan = new People('张三')
zhangsan.sayHi()    // zhangsan对象

手写bind函数

Function.prototype.bind1 = function () {
    // 将参数拆解为数组,arguments可以获取函数所有参数,是列表形式
    const args = Array.prototype.slice.call(arguments)
    // 获取 this (数组第一项)
    const t = args.shift() // shift返回数组第一项,且从原数组中去除第一项
    const self = this      // this是调用bind的函数,fn1.bind(...)中的fn1
    // 返回一个函数
    return function () {
        return self.apply(t, args)
    }
}

function fn1 (a, b, c) {
    console.log('this', this)
    console.log(a, b, c)
    return 'this is fn1'
}
const fn2 = fn1.bind1({x:100}, 10, 20, 30)
const res = fn2()
console.log(res)

实际开发中闭包的应用场景,举例说明

  • 隐藏数据
  • 如做一个简单的cache工具
// 闭包隐藏数据,只提供 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'))