vue3页面空白-普通函数和箭头函数提升的不同

在 JavaScript 中,普通函数(即使用 function 关键字定义的函数)和箭头函数(使用 () 和 => 定义的函数)在作用域和提升(hoisting)行为上有不同的表现。

1. 普通函数(Function Declarations) 普通函数声明会被提升(hoisted),也就是说,它们可以在声明之前被调用。这是因为函数声明会被提升到当前作用域的顶部。例如:

javascript 复制代码
console.log(foo()); // 输出 "Hello"

function foo() {
  return "Hello";
}

在这个例子中,尽管 foo 函数是在调用之后才声明的,但它仍然可以正常工作,因为函数声明会被提升。

2. 箭头函数和其他函数表达式 箭头函数和其他函数表达式(如使用 var, let, const 定义的函数)不会被提升。这意味着它们必须在声明之后才能被调用。例如:

javascript 复制代码
console.log(bar()); // 报错:TypeError: bar is not a function

const bar = () => {
  return "World";
};

在这个例子中,如果尝试在 bar 函数声明之前调用它,会导致错误,因为 bar 在声明之前只是一个未定义的标识符。


错例

javascript 复制代码
watchEffect(() => {
  if(calculateWinner(squareValues.value)){
    status.value = 'Winner: ' + calculateWinner(squareValues.value) + ' ! ';
  }
  else if(!squareValues.value.filter(item => item === '').length){
    status.value = 'Draw !';
  }
  else{
    status.value = 'Next player is ' + (xIsNext.value ? 'X' : 'O');
  }
});

const calculateWinner = (squares) => {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];

  for(let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if(squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }

  return null;
}
相关推荐
李纲明1 天前
WordPress外贸成品网站的免费获取渠道
vue·php
加洛斯1 天前
前端小知识002:ref 与 reactive 详解
前端·vue
计算机毕设vx_bysj68692 天前
计算机毕业设计必看必学~Springboot教学进度管理系统,原创定制程序、单片机、java、PHP、Python、小程序、文案全套、毕设成品等!
java·spring boot·vue·课程设计·管理系统
小贺要学前端2 天前
【无标题】
前端·javascript·vue·技术趋势
IT教程资源C3 天前
(N_141)基于springboot,vue网上拍卖平台
mysql·vue·前后端分离·拍卖系统·springboot拍卖
IT教程资源C3 天前
(N_144)基于微信小程序在线订餐系统
mysql·vue·uniapp·前后端分离·订餐小程序·springboot订餐
合作小小程序员小小店3 天前
web网页开发,在线短视频管理系统,基于Idea,html,css,jQuery,java,springboot,mysql。
java·前端·spring boot·mysql·vue·intellij-idea
aiguangyuan3 天前
Vue 3.0 源码解读
vue·前端开发
IT教程资源D6 天前
[N_144]基于微信小程序在线订餐系统
mysql·vue·uniapp·前后端分离·订餐小程序·springboot订餐
是梦终空8 天前
vue下载依赖报错npm ERR node-sass@4.14.1 postinstall: `node scripts/build.js`的解决方法
javascript·npm·vue·node-sass·vue依赖