Syntax error: Illegal return statement in JavaScript

后端 未结 6 1499
南方客
南方客 2021-02-04 23:25

I am getting a really weird JavaScript error when I run this code:



        
6条回答
  •  故里飘歌
    2021-02-04 23:47

    This can happen in ES6 if you use the incorrect (older) syntax for static methods:

    export default class MyClass
    {
        constructor()
        {
           ...
        }
    
        myMethod()
        {
           ...
        }
    }
    
    MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
    
    MyClass.anotherMethod() //or
    MyClass.anotherMethod = function()
    {
       return something; //doesn't work
    }
    

    Whereas the correct syntax is:

    export default class MyClass
    {
        constructor()
        {
           ...
        }
    
        myMethod()
        {
           ...
        }
    
        static anotherMethod()
        {
           return something; //works
        }
    }
    
    MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
    

提交回复
热议问题