Skip to content

this 的指向?

上次更新 2024年9月13日星期五 3:23:41 字数 0 字 时长 0 分钟

  • this 的指向一般指向函数调用者,也有可能指向全局,严格模式下指向 undefinded
  • 箭头函数 this 指向外层函数的 this

说出下面的代码的输出

javascript
function foo() {
  console.log(this.a);
  var a = 2;
  return this.a; // undefined
}
foo(); // undefined
javascript
const obj = {
  a: 1,
  foo() {
    console.log(this.a);
  },
};
obj.foo(); // 1
javascript
const obj = {
  a: 1,
  foo: () => {
    console.log(this.a);
  },
};

改变 this 指向的方法?

  • call apply bind

它们区别?

  • call 可以改变 this 指向,并且可以传参数 并执行函数
  • apply 可以改变 this 指向,并且可以传参数,但是参数是数组
  • bind 可以改变 this 指向,并且可以传参数,但是不会执行函数,不会执行函数,而是返回一个函数,需要手动调用