节点中是否悬挂了箭头功能? [英] Arrow Function Hoisting in Node?

查看:96
本文介绍了节点中是否悬挂了箭头功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在理解我的代码为什么起作用时,我遇到了一些麻烦.我预计会出现参考错误,但是一切正常.

I'm having a bit of trouble understanding why my code works. I'm expecting a reference error, but everything works fine.

我的代码:

const functionA = () => {
  let bResult = functionB();

  console.log("Function A " + bResult);
};

const functionB = () => {
  return "Function B";
};

functionA();

我得到这个输出(没有错误);

I get this output (no errors);

λ node test.js
Function A Function B

据我了解,仅悬挂函数声明(不悬挂函数表达式) http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html .

As I understand it, only function declarations are hoisted (not function expressions) http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html.

因此,我不应该期待一个错误,因为在FunctionA中调用FunctionB之前没有定义FunctionB吗?我在这里某个地方想念吗?

Thus, shouldn't I expect an error as FunctionB isn't defined before it's called in FunctionA? Am I missing somewhere here?

谢谢大家的回答,我想我已经知道了.确实没有被取消,因为如果我一开始调用functionA,它将给我一个错误.

Thanks for the answers everyone, I think I figured it out. It's indeed not getting hoisted because if I call functionA at the beginning, it gives me an error.

functionA(); // ReferenceError: functionA is not defined

const functionA = () => {
  let bResult = functionB();

  console.log("Function A " + bResult);
};

const functionB = () => {
  return "Function B";
};

因此,这不是起吊的问题.相反,在文件末尾调用functionA时,已经定义了functionA和functionB.

So it's not a question of hoisting. Rather, by the time functionA is called at the end of the file, both functionA and functionB have been defined.

推荐答案

正如其他人指出的那样,在调用functionA时,现在将functionB加载到内存中.

As someone else pointed out, by the time functionA is called, functionB is now loaded into memory.

比较以下内容:

const functionA = functionB;

const functionB = () => {
  return "Function B";
};

functionA();

这将引发未捕获的ReferenceError:未定义functionB"

This will throw 'Uncaught ReferenceError: functionB is not defined'

将此行为与该行为进行比较:

Compare that behavior to this:

const functionA = functionB

function functionB(){
  return "Function B";
};

functionA();

第二个实际上起作用,因为functionB悬挂在常量声明的上方.

The second one actually works, because functionB is hoisted above your constant declaration.

这篇关于节点中是否悬挂了箭头功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆