当const被声明时,它存储在哪里?

3

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

例如:

const a = 'HI!';

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

hello();

这会记录下未定义的内容。

除了使用

global.a = 'HI!'

进行赋值,还有其他方法可以使用this来访问a吗?


1
const 不像 var 一样在全局对象中创建属性。使用变量名引用变量。请注意,在严格模式下,hello 中的 this 将是 undefined,您的代码将抛出错误。 - Teemu
你为什么特别想通过this访问 a - VLAZ
相关内容请参考:https://dev59.com/jl4b5IYBdhLWcg3wtjpA,但可能不是重复的问题,因为主题是“let”。 - Teemu
3个回答

3

如果您想访问一个在外部作用域中的 const 或者 let 变量(它们在访问方面是相同的), 您可以通过名称来访问它。

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()是等效的,但在一般情况下,当传递更多参数时,它们有微妙的区别。了解更多

我有点困惑,你的意思是说如果我在全局范围内使用 const 声明一个变量 _a_,我仍然不能使用 global.a 访问它? - hkisthebest
@user8480342 当在全局作用域中声明letconst变量时,它们不会向全局对象添加属性。这是它们规范的写法,因此行为与之一致。这与在全局作用域中声明的var声明不同,后者明确将属性添加到全局对象中。 - VLAZ
明白了。感谢您的回复! - hkisthebest

2

const 相关信息:

使用 const 关键字可以定义不可变的变量(常量)。

const PI = 3.1415;
PI = 5; // "TypeError: Assignment to constant variable.

然而,仍然可以将新项推入数组常量或添加到对象中。

const someArr = [3, 4, 5];
someArr.push(6);

现在,使用this关键字访问function内部的值,只会为函数块作用域提供值。

因此,要访问函数内部的常量a,您可以使用:

const a = 'HI!';

function hello() {
  console.log(this.a); // undefined <- this refer to function hello's scope
  console.log(a);   // HI!
}

你好!感谢您的回复。在您的最后一段代码中,我在 hello 函数中添加了 var a = 'Hello~',但它仍然输出 undefined。如果 this 指的是函数 hello 的作用域,为什么我仍然无法访问它呢?我认为当您在对象外声明一个函数时,this 简单地表示全局对象,因为在全局范围内记录 this 将返回 window 对象或 global 对象。 - hkisthebest
你可以在hello函数的console log中直接访问变量a,无需使用this.a。 - Saurabh Mistry

1

它在你所处的代码块中声明。你仍然可以从相同的作用域(以及在其中声明的作用域)访问它,但不能使用window.a或global.a从任何作用域访问。

因此,这将起作用:

const a = 1;

function b() {console.log(a);}

然而,以下内容不会:
window.a;
global.a;

箭头函数在这里并不是必需的,该函数将成为闭包。Closure - James
真的 - 我编辑了这篇文章,让它变得更加清晰。@James - Pärt Johanson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接