Vue 2.7 中是否忽略了提升(hoisting)?

huangapple go评论58阅读模式
英文:

Is hoisting ignored in vue2.7?

问题

The code you provided seems to contain JavaScript and Vue.js code snippets. Here are the translated portions:

const test2 = () => {
  test();
};
test2();
const test = () => console.log("test");
const test2 = () => {
  test();
};
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>
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <button @click="test2">button</button>
  </div>
</template>

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.

I hope this helps with your request for translation.

英文:
const test2 = () =&gt; {
  test();
};
test2();
const test = () =&gt; console.log(&quot;test&quot;);

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

 test();
  ^

ReferenceError: Cannot access &#39;test&#39; before initialization
&lt;template&gt;
  &lt;div id=&quot;app&quot;&gt;
    &lt;img alt=&quot;Vue logo&quot; src=&quot;./assets/logo.png&quot; /&gt;
    &lt;button @click=&quot;test2&quot;&gt;button&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
const test2 = () =&gt; {
  test();
};
const test = () =&gt; console.log(&quot;test&quot;);
&lt;/script&gt;

&lt;style&gt;&lt;/style&gt;

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.

Vue 2.7 中是否忽略了提升(hoisting)?

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

答案1

得分: 2

在您的第一个示例中,事件序列如下:

  1. 定义test2
  2. 调用test2
  3. test2试图调用test,然后出现错误

第4步是定义test,但您从未到达那一步。

在您的第二个示例中,序列如下:

  1. 定义一个模板
  2. 定义test2
  3. 定义test
  4. 单击触发对test2的调用,而test2再调用test

这两者的区别与提升(hoisting)无关,只与何时调用test2有关。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月4日 16:24:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定