Šim*_*das 6 javascript variables
例:
var test = 'global value';
(function() {
var test = 'local value';
// how to get the 'global value' string
})();
Run Code Online (Sandbox Code Playgroud)
鉴于主机环境未知的情况,这意味着我们不能假设可以通过window名称访问全局对象.此外,该函数不允许接收任何参数!
var test = 'global value';
(function() {
var test2 = 'local value';
console.log(test);
})();
Run Code Online (Sandbox Code Playgroud)
真正的解决方案是修复您的代码,这样您就不会隐藏您关心的全局变量。
您始终可以使用全局 eval,它是最可靠的。
var test = 'global value';
function runEval(str) {
return eval(str);
}
(function() {
var test = 'local value';
console.log(runEval("test"));
})();
Run Code Online (Sandbox Code Playgroud)
如果您不喜欢定义全局 eval,您可以使用Function间接执行此操作
var test = 'global value';
(function() {
var test = 'local value';
console.log(new Function ("return test;") () );
})();
Run Code Online (Sandbox Code Playgroud)
以下工作在非严格模式下
(function () {
var test = "shadowed";
console.log(this !== undefined && this.test);
})();
Run Code Online (Sandbox Code Playgroud)
这个黑客可以在损坏的实现中工作
(function() {
var test = 'local value';
try { delete test; } catch (e) { }
console.log(test);
})();
Run Code Online (Sandbox Code Playgroud)