var myVar = 5;
var example = function() {
var myVar = 10;
// How can I access the global variable 10?
};
Run Code Online (Sandbox Code Playgroud)
如果存在与局部变量同名的全局变量,如何访问全局变量?
我没有使用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 })Run Code Online (Sandbox Code Playgroud)