Help Inspire
Help Inspire

Reputation: 366

How to Call a Variable from another Function within the same Object?

I just wish to know if there is a simple way to call a variable from another function within the same Object?

var comedy = {
schadenfreude: function() {
    var number = prompt("Provide me a number.");
},
irony: function() {
    this.schadenfreude();
    for(i = 0; i < this.schadenfreude.number(); i++){
        return i;
    }
}
};
console.log(comedy.irony());

In this example I wish to grab the var number from the schadenfreude function and use that prompted number in my for loop with the irony function. Thanks for the help.

Upvotes: 0

Views: 122

Answers (2)

Pointy
Pointy

Reputation: 414006

The "number" variable in your "schadenfreude" function is local to that function. Even if you could get to it (you can't), it would do you no good.

What you (probably) want is:

var comedy = {
    number: 0,
    schadenfreude: function() {
        this.number = prompt("Provide me a number.");
    },
    irony: function() {
        this.schadenfreude();
        for(i = 0; i < this.number; i++){
            alert(i);
        };
    }
};
console.log(comedy.irony());

Alternatively, you could have "schadenfreude" assign the value to a "number" property on the object, so that you'd refer to this.number in the "irony" function. In either case, as I noted in the comment in the code, the fact that your for loop has that return statement means that the "irony" function will always return zero if the user gives you any non-negative number, and undefined otherwise.

Upvotes: 4

JaredPar
JaredPar

Reputation: 755507

It sounds like you want to grab a local variable from another member defined on the same object. That's not directly possible. Local variables are scoped to the defining function / member and there isn't a way to access them directly. The function must explicitly return them to the caller in some manner for them to be accessed

Upvotes: 0

Related Questions