user2781855
user2781855

Reputation: 39

How to defined Global variable scop in javascript

I want to use a variable inside another function but is not defined! I tried it with this and var. how can I make it defined in another function? in the code below, I want to add actionInt by 1 in "next" but it is not defined. any idea?

        func1 : function(event) {

            if (action == "test"){
                console.log(test clicked);
            }


            else if (action == "test2"){

                console.log(test2 clicked);
            }



        },

Upvotes: 0

Views: 73

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

that's because actionInt was declared in this line:

var actionInt = parseInt(action);

And you're incrementing this.actionInt++, where this is the call context, determined ad-hoc (probably the object to which you attached the event listener).
I strongly recommend you read up on what this actually references in JS, just like I'd also suggest you specify the radix when using parseInt, and realize that this doesn't make sense:

actionInt = parseInt(action, 10);//action is number?
if (action === 'next')//action is string?

if action is next or previous, parseInt will always return NaN, which, when incremented, still is NaN (Not A Number + 1 is Not A Number)

But which ever way you look at it, I think you're actually looking for a closure:

onPageClick : (function(actionInt)
{
    return function(event)
    {
        var action = event.target.innerHTML;
        this.loadPage(actionInt, 25);//what is this?
        if (action == "Next"){
            console.log(actionInt++);//no this
        }
        else if (action == "previous"){
            console.log(actionInt--);
        }
    };
}(0)),//pass initial actionInt value here

Refer to this answer on details on how JS resolves expressions/variable names and how closures work...
If actionInt is a global variable, you can omit the IIFE, and just use actionInt, it'll resolve to the global variable by default (or throw an error if it wasn't defined in strict mode)

Upvotes: 1

lukas.pukenis
lukas.pukenis

Reputation: 13597

In your case this refers to global scope(probably) - window object.

In such case as yours there's no need to use this.variable = 0 just use var variable = value;

Upvotes: 0

Related Questions