我想修改下面的代码,从'a'变量列出“hello world”,但不将它传递给函数。可能吗?覆盖全局变量
var a = "declared variable";
var fc = function() {
console.log(a);
};
(function() {
var a = "hello world";
fc();
})();
编辑:啊抱歉...我没有提到。我不想修改全局变量。我只想获得“范围”变量值。
我想修改下面的代码,从'a'变量列出“hello world”,但不将它传递给函数。可能吗?覆盖全局变量
var a = "declared variable";
var fc = function() {
console.log(a);
};
(function() {
var a = "hello world";
fc();
})();
编辑:啊抱歉...我没有提到。我不想修改全局变量。我只想获得“范围”变量值。
你可以这样做。
window.a = "Hello world"
只需卸下var
var a = "declared variable";
var fc = function() {
console.log(a);
};
(function() {
a = "hello world";
fc();
})();
的VAR定义在当前的范围内可变。
作为对编辑的反应,访问作用域的唯一方法是在其中(或将其作为参数传递)。因为你不想传递它,这是我看到的唯一的其他选项。
var a = "declared variable";
(function() {
var fc = function() {
console.log(a);
};
var a = "hello world";
fc();
})();
或者,如果你想要通过范围沿着这样的结构将工作
var a = "declared variable";
var fc = function (scope) {
console.log(scope.a);
};
(function() {
this.a = "hello world";
fc(this);
}).apply({});
非常技术上说这不是你一起传递的范围,但如何它会完成。
感谢您的回答,顺便说一句,如何通过论据传递范围?你能举个例子吗?编辑:nvm:http://stackoverflow.com/questions/6348852/javascript-pass-scope-to-another-function – user1855877
非常感谢。 – user1855877
var a = "declared variable";
var fc = function() {
console.log(a);
};
(function() {
var a = "hello world";
this.a = a; // assign a to global a
fc();
})();
没有做Op的要求。 –
让我给你一个替代的答案。 千万不要这样做。这是一个丑陋的破解,它会更快或更快地破解,它很难调试,并会减慢你的速度。不要懒惰,绕过那个该死的价值,从长远来看它会为你节省大量时间。
所以我的答案是,你不能没有经过a
正常,你想要的东西实现。
它是否可以,如果它失去了''声明变量“'价值? –