I have a class Squierell. squirell1.jump() method in Squrell returns undefined.no errors in console. Maybe I missed something important in syntax?
class Squirrel {
constructor(name, color) {
this.name = name;
this.color = color;
}
get name() {
return this._name;
}
set name(name) {
if (typeof name !== "string") {
throw TypeError;
} else {
this._name = name;
}
}
get color() {
return this._color;
}
set color(color) {
if (typeof color !== "string") {
throw TypeError;
} else {
return (this._color = color);
}
}
jump() {
return this._name + " jumping";
}
}
try {
const squirell1 = new Squirrel("noname", "red");
squirell1.jump();
} catch (error) {
console.log(error.message);
}
Did I define constructor correctly?
>Solution :
In your code, the issue seems to be with the way you are calling the methods of your classes. You are correctly creating instances of the classes, but you are not capturing the returned values from the methods correctly. Additionally, there’s a small typo in your last console.groupEnd.
Here’s a simple and easy-to-understand explanation of what’s happening and how to fix it:
squirell1.jump();in theSquirrelclass returns a string, but you are not capturing it in any variable or printing it to the console. So, it appears as if nothing is happening.
To fix this, you can either capture the returned value in a variable and then console.log it:
const jumpResult = squirell1.jump();
console.log(jumpResult); // Output: "noname jumping"
Or directly console.log the result of the method call:
console.log(squirell1.jump()); // Output: "noname jumping"
- In the
SquirrelFlyclass, you are callingsquirell2.jump()andsquirell2.fly(), but you are not capturing the returned values or printing them to the console.
To fix this, you can do the same as before, capture the returned values and then console.log them:
const jumpResult = squirell2.jump();
const flyResult = squirell2.fly(1000);
console.log(jumpResult); // Output: "belka jumping"
console.log(flyResult); // Output: "belka flying1000"
- In the
SquirrelMagicclass, you are callingsquirell3.speak(), but you are not passing any arguments to thespeakmethod.
To fix this, you can pass the wordsArray argument while calling the method:
squirell3.speak(["wooow", "mew"]);
After making these changes, your code should work as expected, and the methods will return the correct values and output them to the console.