this

106 阅读1分钟

this指向:

1.默认绑定->window

2.隐式绑定->直接调用的对象

3.显式绑定->call apply bind

4.new绑定->新对象

5.箭头函数->定义时绑定(定义时外面的this指向什么箭头函数中的this就指向什么)

改变函数体内的this指向的方法:

1.apply

Function.prototype.myApply = function(context = window, ...args) {
  let key = symbol('key')
  context[key] = this
  let res = context[key](args)
  delete context[key]
  return res
}

function fn(b, c) { console.log(this.a + b + c) }
let obj = { a: 1 }
fn.apply(obj, [2, 3])
// 6

2.call

Function.prototype.myCall = function(context = window, ...args) {
  let key = Symbol('key')
  context[key] = this
  let res = context[key](...args)
  delete context[key]
  return res
}

function fn(b, c) { console.log(this.a + b + c) }
let obj = { a: 1 }
fn.myCall(obj, 2, 3)
// 6

3.bind

Function.prototype.myBind = function(context = window, ...outerArgs) {
  let self = this
  return function fn(...innerArgs) {
    if(self instanceof fn) {
      return new self(...outerArgs, ...innerArgs)
    }
    return self.apply(context, [...outerArgs, ...innerArgs])
    //return self.call(context, ...outerArgs, ...innerArgs)
  }
}

function fn(b, c) { console.log(this.a + b + c) }
let obj = { a: 1 }
fn.myBind(obj, 2, 3)()
// 6