文章
2025年10月29日
JS 基础-作用域闭包

JS 基础-作用域闭包

作用域描述了变量的合法的使用范围

闭包

闭包是作用域应用的特殊情况,有两种表现:函数作为参数被传递和函数作为返回值被返回。 自由变量的查找,是在函数定义的地方向上级作用域查找,不是在执行的地方。

// 函数作为参数被传递
function print(fn) {
  let a = 200
  fn()
}

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

let fn = create()
let a = 200
fn() // 100

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

function fn1() {
  console.log(this)
}
fn1() // window

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

const fn2 = fn1.bind({ x: 200 })
fn2() // { x: 200 }
const people = {
  name: 'zhang',
  sayHi() {
    console.log(this) // 当前对象
  },
  wait() {
    setTimeout(function() {
      console.log(this) // window
    }, 1000)
  },
  waitAgain() {
    setTimeout(() => {
      console.log(this) // 当前对象
    })
  }
}
class Person {
  constructor(name) {
    this.name = name
  }
  sayHi() {
    console.log(this)
  }
}

const p = new Person('zhang')
p.sayHi() // p 对像

改变 this 三种方式

方法参数立即执行
callarg1, ..., argN
applyargsArray
bindarg1, ..., argN返回函数,需要手动调用
© 2025-present Tszkong Cheng. All Rights Reserved.