1

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();
}
2
  • 1
    javaScript variables are scoped to the functions they are defined in. Commented Mar 19, 2014 at 14:11
  • This should do: jsfiddle.net/lshettyl/7Murm Commented Mar 19, 2014 at 14:23

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.