Javascript中的对象和方法出错

时间:2011-11-18 10:00:34

标签: javascript oop

我刚开始使用JOP上的OOP。我是编程世界的新手。你能帮我解决下面的代码吗?我的文本编辑器在'else'块上显示语法错误。

function Dog(name, breed, weight) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.bark = function () {
        if (this.weight > 25) alert(this.name + " says Woof")
    } else {
        alert(this.name + " says Poof");
    }
}

var fido = new Dog("Fido", "Mixed", 38);

fido.bark();

5 个答案:

答案 0 :(得分:2)

{之后的if (this.weight > 25)以及.fido之间的bark();

function Dog(name, breed, weight){
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.bark = function(){
        if (this.weight > 25){
            alert(this.name + " says Woof")
        } else {
            alert(this.name + " says Poof");
        }
    }
}

var fido = new Dog("Fido", "Mixed", 38);
fido.bark();
  1. 你需要适当的缩进才能更容易地看到这样的东西。
  2. 我认为你的运行时投诉是关于else的,因为它在函数之外并且没有“附加”到if,因为缺少括号。
  3. 也许JavaScript不是学习编程的语言。你只是玩游戏学习,还是试着完成任务?

答案 1 :(得分:1)

if (this.weight > 25)
   alert(this.name + " says Woof")
}
else {
  alert(this.name + " says Poof");
}

你不打开if {

答案 2 :(得分:1)

function Dog(name, breed, weight){
this.name = name;
this.breed = breed;
this.weight = weight;
this.bark = function(){
if (this.weight > 25){
alert(this.name + " says Woof")
}
else {
alert(this.name + " says Poof");
}
}
}

var fido = new Dog("Fido", "Mixed", 38);

fido bark();

答案 3 :(得分:1)

试试这个

function Dog(name, breed, weight){
this.name = name;
this.breed = breed;
this.weight = weight;
this.bark = function(){
        if (this.weight > 25){
           alert(this.name + " says Woof");
        }
        else {
          alert(this.name + " says Poof");
        }
    };
}

var fido = new Dog("Fido", "Mixed", 38);

fido.bark();

答案 4 :(得分:0)

if (this.weight > 25)
   alert(this.name + " says Woof")
}

出了问题,你错过了{。它应该是:

if (this.weight > 25)
{
   alert(this.name + " says Woof")
}