英文:
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 = () => {
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.
Do you know why it works without error?? Thanks!
答案1
得分: 2
在您的第一个示例中,事件序列如下:
- 定义test2
- 调用test2
- test2试图调用test,然后出现错误
第4步是定义test,但您从未到达那一步。
在您的第二个示例中,序列如下:
- 定义一个模板
- 定义test2
- 定义test
- 单击触发对test2的调用,而test2再调用test
这两者的区别与提升(hoisting)无关,只与何时调用test2有关。
英文:
In your first example, the sequence of events is:
- define test2
- call test2
- 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:
- define a template
- define test2
- define test
- click which triggers a call to test2 which calls test
The difference has nothing to do with hoisting, just with when test2 is called.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论