var myVar = 5;
var example = function() {
var myVar = 10;
// How can I access the global variable 10?
};
如果有一个与本地变量同名的全局变量,我该如何访问全局变量?
我没有使用es6。
我在jsdb中运行它,而不是在浏览器或节点中,因此我无法访问对象'Window'或'global'。
var myVar = 5;
var example = function() {
var myVar = 10;
// How can I access the global variable 10?
};
如果有一个与本地变量同名的全局变量,我该如何访问全局变量?
我没有使用es6。
我在jsdb中运行它,而不是在浏览器或节点中,因此我无法访问对象'Window'或'global'。
example()
函数的代码,您应该能够使用Function.prototype.call()
传递当前作用域,并使用this
访问它。例如:
'use strict'
var myVar = 5;
var example = function() {
var myVar = 10;
console.info('Local:', myVar)
console.info('Outer:', this.myVar)
};
example.call({ myVar })
this
访问函数的上下文。Function.prototype.call
的好处在于可以提供这个上下文。例如,如果你使用.call({a: 1})
,那么this.a
将会是1
。 - Phil
example()
函数的?你能修改那段代码吗? - Phil