Skip to content

函数

调用模式

1. 直接调用

js
function hello() {
  console.log(this.age) // => undefined
}

this 在非严格模式下为 window ,在严格模式下等于 undefined

2. 对象调用

js
const p = {
  age: 12,
  hello() {
    console.log(this.age) // => 12
  }
}

p.hello()

this 指向调用的对象。

3. 显示绑定调用

js
function hello() {
  console.log(this.age) // => 12
}

hello.call({
  age: 12
})

this 指向绑定的对象。

4. 构造函数调用

js
function Person() {
  this.age = 12
  console.log(this.age) // => 12
}

const p = new Person()

this 指向当前对象。

优先级 重要

箭头函数

箭头函数相较于普通函数的不同点:

  • 箭头函数的 this 绑定为其词法作用域

手写系列

手写 bind

实现原理

当函数以对象成员的方式进行调用时,会自动绑定当前对象作为this,此polyfill就是利用了这个特性。

ts
function bind(fn: Function, thisArg: any, ...presetArgs: any[]) {
  const context = thisArg || window
  const fnSymbol = Symbol('fn')
  context[fnSymbol] = fn
  return function(...args: any[]) {
    return context[fnSymbol](...presetArgs, ...args)
  }
}