简体   繁体   中英

Error on Objects and methods in Javascript

I just started with OOP on Javascript. I am new to programming world. Could you please help me on the following code? My text editor shows syntax error on 'else' block.

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();

You are missing a { after if (this.weight > 25) as well as a . between fido and 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. You need proper indention to see stuff like this more easily.
  2. I think your runtime complaint about the else, because it was outside the function and not "attached" to the if, because of the missing brackets.
  3. Maybe JavaScript isn't the language to learn programming. Do you just play around to learn or do you try to get something done?
if (this.weight > 25)
   alert(this.name + " says Woof")
}
else {
  alert(this.name + " says Poof");
}

your not opening the if {

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();

Try this

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();
if (this.weight > 25)
   alert(this.name + " says Woof")
}

is where its gone wrong, you're missing a { . It should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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