this指向问题

72 阅读1分钟

[TOC]

this 绑定

默认绑定

function foo() {
  console.log("fpp", this);
}
foo();
let obj = {
  name: "gmx",
  bar: function () {
    console.log("bar", this);
  },
};

let bar = obj.bar;
bar();

严格模式下,独立调用的函数中的 this 所指向的是 undefined

隐式绑定

function foo() {
  console.log("foo");
}

let obj = {
  bar: foo,
};

obj.bar();

显示绑定

apply call bind

new 绑定

  • 1.创建新对象
  • 2.将 this 指向这个对象
  • 3.执行函数体中的代码
  • 4.没有显示返回非空对象时,默认返回这个对象

this 绑定优先级

默认绑定的优先级最低 显示绑定的优先级高于隐式绑定的优先级 new 优先级高于隐式绑定 new 不可以和 apply call 一起使用 new 绑定优先级高于 bind

this 绑定之外的情况

传入 null,undefined 采用默认绑定