'this' is undefined in JavaScript class methods

前端 未结 5 1065
悲&欢浪女
悲&欢浪女 2020-12-13 11:51

I\'m new to JavaScript. New as far as all I\'ve really done with it is tweaked existing code and wrote small bits of jQuery.

Now I\'m attempting to write a \"class\"

5条回答
  •  暖寄归人
    2020-12-13 12:16

    This question has been answered, but maybe this might someone else coming here.

    I also had an issue where this is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:

    import MyClass from "./myClass"
    
    // 'this' is not defined here:
    const { aMethod } = new MyClass()
    aMethod() // error: 'this' is not defined
    
    // So instead, init as you would normally:
    const myClass = new MyClass()
    myClass.aMethod() // OK
    
    

提交回复
热议问题