4

I would like to modify following code to list "hello world" from 'a' variable without passing it to function. Is it possible?

var a = "declared variable";

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

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

edit: Ah sorry ... I haven't mentioned. I don't want modify global variable. I just want get "scope" variable value.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
user1855877
  • 81
  • 1
  • 5

4 Answers4

1

Just remove the var

var a = "declared variable";

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

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

The var defines the variable in the current scope.


In reaction to the edit, the only way to access the scope is to be in it (or pass it along as an argument). As you don't want to pass it along this is the only other option I see.

var a = "declared variable";

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

Or if you would want to pass the scope along a construction like this would work

var a = "declared variable";

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

(function () {
  this.a = "hello world";
  fc(this);
}).apply({});

Very technically speaking it's not the scope you're passing along, but this is how it would be done.

David Mulder
  • 26,123
  • 9
  • 51
  • 114
  • Thanks for answer, btw how to pass scope by argument? Can u show example? edit: nvm: http://stackoverflow.com/questions/6348852/javascript-pass-scope-to-another-function – user1855877 May 31 '13 at 12:19
0

Let me give you an alternative answer. Don't ever do that. This is an ugly hack that will break sooner or sooner, it is hard to debug and will slow you down. Don't be lazy, pass around that damn value, it will save you lots of time in the long run.

So my answer is, you can't achieve properly what you want without passing a.

zupa
  • 12,809
  • 5
  • 40
  • 39
-2

You can do it like this.

window.a = "Hello world"
Filip Minx
  • 2,438
  • 1
  • 17
  • 32
-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();
}) ();
Darshan
  • 750
  • 7
  • 19