this小记

88 阅读1分钟

this指向

一般情况下,this指向最近的调用者

this优先级:

箭头函数-->new-->bind-->applycall-->obj.-->直接调用-->不在函数里

特殊情况:

  • 箭头函数的this需要看其父级作用域,且其this在函数被定义时产生;

  • new 能够改变 bind 指定的 this;

  • apply和call无法改变bind指定的this;

  • 多次 bind 时只认第一次 bind 的this值;

改变 this 的指向的方法:

  1. 使用箭头函数(例:在setTimeout内部使用箭头函数改变this)

  2. 在函数内部使用变量保存 this

  3. 使用 applycallbind

  4. new 实例化一个对象