Why can't I use a Javascript function before its definition inside a try block?

后端 未结 3 595
野趣味
野趣味 2020-12-01 13:42

As discussed here, function definitions can be used before they\'re defined. But as soon as a section of code is wrapped in a try block, this ceases to be the case.

3条回答
  •  死守一世寂寞
    2020-12-01 14:22

    You can always do it this way and get the best of both worlds:

    function hello() {
      alert("Hello world");
    }
    
    try {
      hello();
    }
    catch (err) {
      alert(err);
    }
    

    You will still get your exceptions in the catch block, but the function will be available. It should be easier to maintain as well, and there is no functional benefit to hoisting functions anyway.

    Edit:

    To demonstrate that this is just as durable as enveloping the entire code in a try catch, I'm providing a more detailed example.

    function hello(str) {
      alert("Hello, " + str);
    }
    
    function greet() {
      asdf
    }
    
    try {
      var user = "Bob";
      hello(user);
      greet();
      asdf
    }
    catch (e) {
      alert(e);
    }
    

    This will work as expected, no parsing issues. The only locations where it could fail at load time are outside of the function defs and the try catch. You will also get exceptions on any garbage inside of the function defs.

    I guess it's a style preference, but it seems to be more readable and maintainable to me than other options.

提交回复
热议问题