简体   繁体   English

如何在javascript中定义全局变量

[英]how to define global variable in javascript

I am wondering how I can define a global variable in javascript. 我想知道如何在javascript中定义全局变量。 That's what I am doing and I want currentValue to be global so everytime gotoNext and previous function can change its value 这就是我正在做的,我希望currentValue是全局的,以便每次gotoNext和上一个函数都可以更改其值

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! 但在goToNext和gotoPrevious中未定义currentValue!

You're not really asking about a global variable, but a class level variable. 您并不是真正在问一个全局变量,而是一个类级别的变量。

You need to set this.currentValue = event.target.innerHTML; 您需要设置this.currentValue = event.target.innerHTML;

You need to define currentValue outside of any function scope. 您需要在任何函数范围之外定义currentValue。 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: IMO,定义对象的最佳方法如下:

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/ http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM