我是JS的新手,在阅读mozilla.org的文档时,我看到当在全局声明const
时,它不会成为全局对象的属性。我的问题是,如果不是这样,属性存储在哪里?
例如:
const a = 'HI!';
function hello() {
console.log(this.a); // undefined
}
hello();
这会记录下未定义的内容。
除了使用
global.a = 'HI!'
进行赋值,还有其他方法可以使用this
来访问a
吗?
我是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()
是等效的,但在一般情况下,当传递更多参数时,它们有微妙的区别。了解更多。const
声明一个变量 _a_,我仍然不能使用 global.a
访问它? - hkisthebestlet
和const
变量时,它们不会向全局对象添加属性。这是它们规范的写法,因此行为与之一致。这与在全局作用域中声明的var
声明不同,后者明确将属性添加到全局对象中。 - VLAZconst 相关信息:
使用 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它在你所处的代码块中声明。你仍然可以从相同的作用域(以及在其中声明的作用域)访问它,但不能使用window.a或global.a从任何作用域访问。
因此,这将起作用:
const a = 1;
function b() {console.log(a);}
window.a;
global.a;
const
不像var
一样在全局对象中创建属性。使用变量名引用变量。请注意,在严格模式下,hello
中的this
将是undefined
,您的代码将抛出错误。 - Teemuthis
访问a
? - VLAZ