js中this专题

54 阅读1分钟

this问题

// bad
  class MyClass {
    constructor() {
      this.value = 42;
    }

    displayValueLater() {
      setTimeout(function() {
        console.log(this.value); // 输出 undefined
      }, 1000);
    }
  }

  const myInstance = new MyClass();
  myInstance.displayValueLater(); // 输出 undefined
// good
    class MyClass {
      constructor() {
        this.value = 42;
      }

      displayValueLater() {
        setTimeout(() => {
          console.log(this.value); // 输出 42
        }, 1000);
      }
    }
    const myInstance = new MyClass();
    myInstance.displayValueLater(); // 输出 42

一个demo


function $catchMsg({ type = "catch", error = {}, response = {} }) {
  if (type === "catch") {
    if (
      error !== null &&
      typeof error === "object" &&
      error.hasOwnProperty("response")
    ) {
      const {
        response: {
          data: { msg },
        },
      } = error;
      this.$msg.error(msg);
      return msg;
    }
  } else {
    this.$msg.error(response?.msg);
    return response?.msg;
  }
}

function $throwCatchMsg({ type = "catch", error = {}, response = {} }) {
  throw new Error(
    $catchMsg.bind(this)({
      type,
      response,
      error,
    })
  );
}