作用域和闭包

知识点

作用域和自由变量

作用域

  • 全局作用域
  • 函数作用域
  • 块级作用域(ES6新增)

自由变量

  • 一个变量在当前作用域内没有定义, 但被使用了
  • 向上一级作用域, 一层一层一次寻找, 知道找到为止
  • 如果全局作用域都没找到, 则报错 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
// PS: 所有的自由变量的查找, 是在函数定义的地方, 向上级作用域查找, 而不是执行的地方

this (this 取值是在函数执行的时候确认的, 不是在函数定义的时候确认)

  • 作为普通函数
  • 使用 call apply bind
  • 作为对象方法被调用
  • 在 class 方法中调用
  • 箭头函数
function fn1 () {
    console.log(this)
}
fn1() // window

fn1.call({ x: 100 }) // {x: 100}

const fn2 = fn1.bind({ x: 200 }) // PS: bind 会返回一个新的函数执行
fn2() // {x: 200}
const zhangsan = {
    name: '张三',
    sayHi () {
        // this 即当前对象
        console.log(this)
    },
    wait () {
        setTimeout (function () {
            // this === window
            console.log(this)
        }, 0)
    }
}
zhangsan.sayHi() // 当前对象
zhangsan.wait() // window
const zhangsan = {
    name: '张三',
    sayHi () {
        // this 即当前对象
        console.log(this)
    },
    wait () {
        // 注意这里使用的是箭头函数, 他的 this 永远是取上层作用域的 this, 他自己本身不具备 this 这个值
        setTimeout (() => {
            // this 即当前对象
            console.log(this)
        }, 0)
    }
}
zhangsan.sayHi() // 当前对象
zhangsan.wait() // 当前对象
class People {
    constructor (name) {
        this.name = name
        this.age = 20
    }
    sayHi () {
        console.log(this)
    }
}
const zhangsan = new People('张三')
zhangsan.sayHi() // 张三这个对象

面试题

this 的不同应用场景, 如何取值?

  • 作为普通函数
  • 使用 call apply bind
  • 作为对象方法被调用
  • 在 class 方法中调用
  • 箭头函数

手写 bind 函数

先来体验下 bind 的用法

function fn1 (a, b, c) {
    console.log(this)
    console.log(a, b, c)
    return 'this is fn1'
}

// bind 第一个参数是 this
const fn2 = fn1.bind({ x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)
/*
打印结果
{x: 100}
test.html:26 10 20 30
test.html:33 this is fn1
*/

手写 bind, 我们来写个 bind1 方法

// 模拟 bind
Function.prototype.bind1 = function () {
    // 将参数拆解为数组
    // arguments 是一个列表, 我们需要把它变成数组
    const args = Array.prototype.slice.call(arguments) // 用 call 把 arguments 变成 Array.prototype.slice 的 this

    // 获取 this (数组第一项)
    const t = args.shift()

    // 上边例子 fn1.bind(...) 中的 fn1, 这里的 this 相当于 class 里, 它代表的就是这个对象的本身
    const self = this

    // 返回函数
    return function () {
        return self.apply(t, args)
    }
}

// 下边改成 bind1 执行一样能实现
function fn1 (a, b, c) {
    console.log(this)
    console.log(a, b, c)
    return 'this is fn1'
}

// bind 第一个参数是 this
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')) // 100

// data.b = 200 这个是会报错的, 找不到闭包中的 data

作用域题目

// 创建 10 个 <a> 标签, 点击的时候弹出来对应的序号
// 这里注意块状作用域, let i 声明在全局, 或者 适用 var 声明, 都会导致点击显示都是 10
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)
}

 

原文地址:https://www.cnblogs.com/helzeo/p/13045066.html