Calling a method from another method in the same class

后端 未结 7 1578
难免孤独
难免孤独 2021-02-05 01:21

Why am I getting the error: \"Uncaught TypeError: self.myTest is not a function\"? How do I call a method from within another method in a javascript class?

7条回答
  •  我寻月下人不归
    2021-02-05 01:59

    You need to use the this keyword instead of self.

    runMyTest() {
        this.myTest();
    }
    

    A side note

    If you are nesting standard functions notation then this is not lexically bound (will be undefined). To get around this, use Arrow Functions (preferred), .bind, or locally define this outside of the function.

    class Test {
      constructor() {
        this.number = 3;
      }
    
      test() {
        function getFirstThis() {
           return this;
        }
    
        const getSecondThis = () => {
           return this;
        };
    
        const getThirdThis = getFirstThis.bind(this);
        
        const $this = this;
        function getFourthThis() {
          return $this;
        }
    
        // undefined
        console.log(getFirstThis());
        
        // All return "this" context, containing the number property
        console.log(this); 
        console.log(getSecondThis());
        console.log(getThirdThis());
        console.log(getFourthThis());
      }
    }
    
    new Test().test();

提交回复
热议问题