Alfath Dirk
Alfath Dirk

Reputation: 83

how to call variable in function object javascript

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

Upvotes: 2

Views: 81

Answers (2)

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 1

vodolaz095
vodolaz095

Reputation: 6986

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());

Upvotes: 0

Related Questions