javascript - const 声明时存储在哪里?

标签 javascript node.js

我是 JS 的新手,在阅读 mozilla.org 的文档时,我读到在全局中声明 const 时,它不会成为全局对象的属性。我的问题是,如果是这样,属性存储在哪里?

例如:

const a = 'HI!';

function hello() {
  console.log(this.a); // undefined
}

hello();

这注销未定义。

而不是分配给它

global.a = 'HI!'

还有其他方法可以使用 this 访问 a 吗?

最佳答案

如果你想访问一个 constlet 变量(它们在访问方面的行为相同)在外部作用域,然后你可以通过名称来完成

const outerVariable = 'HI!';

function hello() {
  console.log("access from inner scope", outerVariable); 
}

hello();

这有效,除非变量被遮蔽 - 在内部范围内创建一个具有相同名称的新变量

const outerVariable = 'HI!';

function hello() {
  const outerVariable = "impossible to access the outer declaration";
  console.log("access from inner scope", outerVariable); 
}

hello();

如果您想使用this 上下文访问它,那么您可以使用Function#call()设置函数的上下文。 , Function#apply() , 或 Function#bind() .

const a = 'HI!';

function hello() {
  console.log("access from context", this.a); 
}

hello(); //undefined - it's not in the context

const newContext = {a : a}; //the new value of "this"
hello.call(newContext); //HI!
hello.apply(newContext); //HI!

const boundFunction = hello.bind(newContext); //"this" will always be newContext for boundFunction
boundFunction(); //HI!

在这种情况下,.call().apply() 是等效的,但一般来说 they are subtly different when more parameters are passed

关于javascript - const 声明时存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55076135/

相关文章:

javascript - 没有 Javascript 的人的后备会在 jQuery 加载之前闪现

javascript - 使用不可序列化参数的 Puppeteer ExposureFunction

node.js - Puppeteer - PDF 生成的不同结果(本地 [windows] 与 live [centos])?

node.js - 如何在 express 中从我的模板目录的根目录中包含/扩展一个 jade 文件?

django - 允许多个用户加入聊天室(使用 Django、Socket.io 和 node.js)

node.js - winston 的 nodejs 应用程序中的日志文件在哪里

javascript - 设置按钮来运行不同的脚本

javascript - ReactJS Koans 杂货 list 第 1 部分

javascript - gwt编译器找不到入口点类

javascript - 具有调整大小事件的等高行