0

I am wondering how I can define a global variable in javascript. That's what I am doing and I want currentValue to be global so everytime gotoNext and previous function can change its value

onPageClick : function(event) { var currentValue = event.target.innerHTML; if (currentValue == "Next") this.gotoNext(); if (currentValue == "previous") this.gotoPrev(); }, gotoNext : function() { this.currentValue +1; }, gotoPrevious : function() { this.currentValue -1; }, 

but currentValue is not defined in goToNext and gotoPrevious!

1

2 Answers 2

3

You're not really asking about a global variable, but a class level variable.

You need to set this.currentValue = event.target.innerHTML;

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

2 Comments

and where should I declare it? outside of function?
You don't need to declare it. Just setting this.foo = 1; is enough.
0

You need to define currentValue outside of any function scope. Like this:

<script> var currentValue = ''; /* YOUR SCRIPT GOES HERE */ </script> 

But then, you must change your code on the two last functions:

gotoNext : function() { currentValue += 1; }, gotoPrevious : function() { currentValue -= 1; } 

But be carefull with this, globale variables are a bad thing. IMO, the best way to define an object is as follow:

var yourObject = function(){ var currentValue = ''; var that = { onPageClick : function(event) { var currentValue = event.target.innerHTML; if (currentValue == "Next") that.gotoNext(); if (currentValue == "previous") that.gotoPrevious(); }, gotoNext : function() { currentValue += 1; }, gotoPrevious : function() { currentValue -= 1; } }; return that; }; 

And then, you use it like this:

var obj = yourObject(); obj.gotoNext(); obj.gotoPrevious(); 

I would advise you to learn about scope and closures :

http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

2 Comments

Thanks you so much, actually there is an event: events : {"click a.a-page-item" : "onPageClick"}, when you click obPaecick function get called. but if I define it inside var yourObject = function(){ it deos not get called.
Could you please create a FiddleJS with your code, so I can help you ? Thx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.