javascriptvuejs2hoisting

Is hoisting ignored in vue2.7?


const test2 = () => {
  test();
};
test2();
const test = () => console.log("test");

The code above returns an error. The command executed is: node file.js

 test();
  ^

ReferenceError: Cannot access 'test' before initialization
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="test2">button</button>
  </div>
</template>

<script setup>
const test2 = () => {
  test();
};
const test = () => console.log("test");
</script>

<style></style>

But the above code works fine in vue. As far as I know the arrow function should throw an error because hoisting doesn't work, but it works fine.

enter image description here

Do you know why it works without error?? Thanks!


Solution

  • In your first example, the sequence of events is:

    1. define test2
    2. call test2
    3. test2 tries to call test and you get an error

    Step 4 would be defining test, but you never get that far.

    In your second example, the sequence is:

    1. define a template
    2. define test2
    3. define test
    4. click which triggers a call to test2 which calls test

    The difference has nothing to do with hoisting, just with when test2 is called.