2

Im learning js , can u help me how to call variable js in object function

example

var obj = {
    a : 'foo',
    b : function(){
        var ab = a + "bar"; <-- how to call var 'ab' outside var obj ..
        alert(ab)
    }
}

console.log(ab);

thanks

3
  • Short answer: you can't. You declared ab as a variable inside the closure of function b. What are you actually trying to do here? You could return ab from the function b or you could make it a member your obj, or you can make it global. Commented Feb 28, 2014 at 19:57
  • i need content of var 'ab' in the object.. Commented Feb 28, 2014 at 19:59
  • @AlfathDirk may I ask why the unaccept? Commented Feb 28, 2014 at 20:34

2 Answers 2

1

There's no way to call it unless your function returns that var. Like this:

var obj = {
    a : 'foo',
    b : function(){
        var ab = a + "bar"; // <-- how to call var 'ab' outside var obj ..
        alert(ab);
        return ab; // this is the key
    }

}

Then, to call it, just use:

var myNewVar = obj.b();

Note: as Benjamin Gruenbaum pointed out (I thought it was obvious, but yeah, it should be mentioned to a beginner definitely), myNewVar won't be a reference of your ab variable, but only have its value.

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

2 Comments

Since strings are values in JS myNewVar is not ab, but just its value. That's not the same. The correct answer is there is no way to modify it from outside the function.
@BenjaminGruenbaum That's very true, I'll add it to my answer, thank you.
0

you need to invoke it as global variable.

var ab;
var obj = { a : 'foo', b : function(){ ab = a + "bar";}
console.log(ab);

or probably you need to output it by return

var obj = { a : 'foo', b : function(){ var ab = a + "bar"; return ab;}
console.log(obj.b());

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.