Haradzieniec
Haradzieniec

Reputation: 9340

javascript: access all variables of a parent function

I decided to create a funcB function that I call from funcA. I want all variables from funcA to be available in the funcB so func B can change that variables. How to modify the code below so it meets my requirements? I doubt passing all variables it the only possible and the best way.

function funcB(){
alert(var1);//how to make it alert 5
alert(var20);//how to make it alert 50
}
function funcA(){
var var1=5;
...
var var20=50;
funcB();
}

Upvotes: 1

Views: 213

Answers (3)

nanobash
nanobash

Reputation: 5500

var obj = {
    one : "A",
    two : "B",
    fnA : function() {
        this.fnB(); // without fnB method result will be displayed as A B, with fnB as C D
        console.log(this.one + " " + this.two);
    },
    fnB : function() {
        this.one = "C";
        this.two = "D";
    }
};

obj.fnA();

this keyword refers to obj object

You can define object with properties and methods inside it. With methods all the variables can be manipulated as you wish, from this example with fnB I'm changing values of properties which are displayed from fnA method

JSFiddle

Upvotes: 2

Harry
Harry

Reputation: 1699

This is not possible as when you declare a variable with the var keyword, they are scoped to the function in which they are declared.

If you avoid the var keyword, they are instead defined as a global variable. This is deemed very bad practice.

I would recommend you read up on javascript coding patterns, particularly the module pattern.

For example:

var myNamespace = (function () {
  var foo, bar;  
  return {
    func1: function() {
      foo = "baz";
      console.log(foo);
    },

    func2: function (input) {
      foo = input;
      console.log(foo);
    }
  };

})();

Usage:

myNamespace.func1();
// "baz"
myNamespace.func2("hello");
// "hello"

Upvotes: 1

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

One way is to drop the var keyword:

function funcB(){
    alert(var1);//how to make it alert 5
    alert(var20);//how to make it alert 50
}

function funcA(){
    var1 = 5;
    var20 = 50;

    funcB();
}

This will expose them to the global scope so funcB can access them. Notice you can also create the varaibles in the global scope itself, with the var keyword, but both methods will ultimately have the same effect.

Note:

  1. This may not work if there is already a var1 or var20 in the global scope. In such case, it will modify the global value and may result in unwanted errors.
  2. This method is not preferred for official code, and is bad practice Reason

Upvotes: 1

Related Questions