单元二之第二章变量提升及其他

66 阅读1分钟

变量提升(Hoisting)

    1. 什么类型有变量提升
    1. 函数类型
    2. var 声明的变量类型
    1. 变量提升的用处
    1. 将代码提升到底部使用

代码

// 优雅写法
import xxx from "././project";
import xxx from "././project";
import xxx from "././project";

// pinia
const storageState = useStorage(),
  mainState = useStorage();

// 声明对象的简写方式
let num1 = ref(0),
  num2 = ref(0),
  num3 = ref(0);

const msg = ref([]),
  msg2 = ref({}),
  msg3 = ref({});

const formData = reactice({}),
  msgData = reactice({});
// 函数声明的位置
const sum = (a, b) => {},
  msg = () => {},
  handleLogin = () => {},
  multiply = (a, b) => a * b;

// 函数声明的位置2
const sum1 = () => {},
  msg = () => {},
  handleLogin = () => {};

sum(6, 2);
msg();
handleLogin();
// 正常写法
sum();

function sum() {
  console.log(num1 + num2);
}

var num1 = 10,
  num2 = 5;

总结

  1. 真正的魔法发生在执行上下文的创建阶段
  2. 我相信要有好的代码结构,应该在顶部建立变量
    1. 在调用函数之前应该始终先建立函数 => 这才是良好的代码结构