覆盖全局变量

4
我想修改以下代码,从 'a' 变量中列出“hello world”,而不需要将其传递给函数。是否可能?
var a = "declared variable";

var fc = function () {
  console.log(a);
};

(function () {
  var a = "hello world";
  fc();
}) ();

编辑:啊,抱歉...我忘了提。我不想修改全局变量。我只想获取“scope”变量的值。


如果“声明的变量”值丢失了,这样做可以吗? - rahul maindargi
4个回答

1

只需删除 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({});

严格来说,你传递的不是作用域,但这就是如何完成的。


谢谢回答,顺便问一下如何通过参数传递作用域?你能给个例子吗?编辑:算了,这里有一个例子:https://dev59.com/iWw15IYBdhLWcg3w3vle - user1855877

0

让我给你一个替代方案。绝对不要这样做。这是一种丑陋的黑客方式,很快就会出问题,难以调试,并会减慢你的速度。不要懒惰,传递那个该死的值,长远来看它会为你节省大量时间。

所以我的答案是,如果不传递a,你无法正确实现你想要的功能。


-2
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 的要求。 - rahul maindargi

-2
你可以像这样做。
window.a = "Hello world"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接