带有命名空间的意外标识符

时间:2019-05-05 10:22:52

标签: javascript namespaces

我有一个简单的代码,可以使div元素在页面上来回移动。一切正常,但是当我尝试使用名称空间时,它不再起作用,并且我收到有关数字0的“意外语法错误:意外标识符”的信息。为什么?您将如何在此处使用命名空间使其工作?我刚刚开始命名空间,发现它有点混乱。

<script>

        var MyNameSpace = MyNameSpace|| {

        var x: 0;
        var y: 20;
        var direction = "droite";

        bouger: function () {

            if (direction == "droite") {
                x:x+1;
            }


            else if (direction =="gauche") {

                x: x-1;
            }

            document.getElementById("bouge").style.left: x + "px";
            document.getElementById("bouge").style.top: y + "px";


            if (x == 200) {
                direction = "gauche";
            }
                else if (x ==0) {
                    direction = "droite";
                }
            }

        setInterval(bouger, 5);

        };

        MyNameSpace.bouger();


    </script>

2 个答案:

答案 0 :(得分:0)

您的代码中存在几个语法错误。 var x:0x: x-1

除此之外,使用||运算符,我们为MyNameSpace分配一个对象常量(如果尚不存在)。您正在{}中为其分配代码块。而是可以将xydirection更改为MyNameSpace的属性,并使用this关键字。而且,您无法在对象文字内调用setInterval(bouger, 5)。因此,您可以在setTimeout函数内部使用bouger在5毫秒后重复该函数:

var MyNameSpace = MyNameSpace || {

  x: 0,
  y: 20,
  direction: "droite",

  bouger: function() {

    if (this.direction == "droite") {
      this.x++;
    } else if (this.direction == "gauche") {
      this.x--;
    }
    
    document.getElementById("bouge").style.fontSize = this.x + "px";
    document.getElementById("bouge").style.top = this.y + "px";

    if (this.x == 200) {
      this.direction = "gauche";
    } else if (this.x == 0) {
      this.direction = "droite";
    }
    
    setTimeout(this.bouger.bind(this), 5);
  }

};

MyNameSpace.bouger();
<div id="bouge">text</div>

style.left不起作用。所以我正在使用fontSize

答案 1 :(得分:0)

var MyNameSpace = MyNameSpace|| {
    x: 0,
    y: 20,
    direction: "droite",
    bouger: function () {
        if (this.direction == "droite") {
            this.x = this.x + 1;
        } else if (this.direction == "gauche") {
            this.x =  this.x - 1;
        }
        document.getElementById("bouge").style.left = this.x + "px"; 
        document.getElementById("bouge").style.top = this.y + "px";
        if (this.x == 200) {
            this.direction = "gauche";
        } else if (this.x ==0) {
            this.direction = "droite";
        }
    }
}
setInterval(bouger, 5)
MyNameSpace.bouger();

我编辑了您的代码以反映命名空间模式的使用方式。它是一个带有属性的对象,在您的代码中仍然有分号和“ var”,这使得命名空间不是对象