我是 JS 的新手,在阅读 mozilla.org 的文档时,我读到在全局中声明 const
时,它不会成为全局对象的属性。我的问题是,如果是这样,属性存储在哪里?
例如:
const a = 'HI!';
function hello() {
console.log(this.a); // undefined
}
hello();
这注销未定义。
而不是分配给它
global.a = 'HI!'
还有其他方法可以使用 this
访问 a
吗?
最佳答案
如果你想访问一个 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()
是等效的,但一般来说 they are subtly different when more parameters are passed
关于javascript - const 声明时存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55076135/