重复变数笑脸

时间:2018-01-17 04:30:39

标签: javascript

我在可汗学院使用此程序重复变量时遇到问题。程序似乎运行正常,但消息通知"两个或多个变量具有相同的名称。作为最佳实践,您应该为变量使用不同的名称。"我无法理解我的生活。

    var SmileyFace = function(centerX, centerY) {
        this.centerX = centerX;
        this.centerY = centerY;
    };

    SmileyFace.prototype.draw = function() {
        fill(255, 234, 0);
        ellipse(this.centerX, this.centerY, 150, 150);
        fill(0, 0, 0);
        ellipse(this.centerX-30, this.centerY-30, 20, 20);
        ellipse(this.centerX+30, this.centerY-30, 20, 20);
        noFill();
        strokeWeight(3);
        arc(this.centerX, this.centerY+10, 64, 40, 0, 180);
    };

    var face = new SmileyFace(200,300);
    face.draw();

    SmileyFace.prototype.speak = function(phrase) {
        text(phrase, this.centerX+100, this.centerY, 100, 100);
    };

    var Smiley = new SmileyFace(100, 300);
    face.draw();
    face.speak("hello");

    var face = new SmileyFace(100, 100);
    face.draw();
    face.speak("Yolo");

    var face = new SmileyFace (90,200);
    face.draw();
    face.speak("Hi");

2 个答案:

答案 0 :(得分:4)

您声明了face变量并初始化了3次。

var face = new SmileyFace(200,300);
var face = new SmileyFace(100, 100);
var face = new SmileyFace (90,200);

给他们不同的名字。可能是face1, face2 and face3

答案 1 :(得分:3)

您将重新声明face变量3次。如果您只是想重新分配它,则无需重新声明它:

var face = new SmileyFace(200,300);
// ...

face = new SmileyFace(100, 100);
// ...

或者,为每个实例使用一个新变量:

var face1 = new SmileyFace(200,300);
// ...

var face2 = new SmileyFace(100, 100);
// ...