如何解决从事面向MERN的Javscript OOP项目:类和构造器
我正在学习有关MERN的类和构造函数,并且被困在算法上。
基本上,这就是我要做的: 创建忍者课程 添加属性:名称 添加属性:健康 增加属性速度;默认为3; 增加属性强度;默认值为3 添加方法sayName();应该记录忍者的名字 添加方法showStats();应该控制台记录所有统计信息(名称,力量,速度和健康状况) 添加方法DrinkSake();应该使健康提高+10
到目前为止,这是我的代码:
class Ninja {
constructor(name,health){
this.speed = 3;
this.strength = 3;
}
sayName() {
this.name = "Lemon";
}
showStats(){
this.name = name;
this.health = health;
this.speed = speed;
this.strength = strength;
console.log(showStats);
}
drinkSake(){
this.health += 10;
}
}
,然后我的构造函数列在函数的底部(我尝试在内部发挥作用,并且还收到错误
const ninja = new Ninja ("lemon",100){
Ninja.sayName();
console.log(ninja.name);
}
在确定新实例的去向时遇到了问题。如果您能使建议尽可能基本,我将不胜感激。
解决方法
这是实现忍者类的一种方式。
// classes get defined at the top of the file since they aren't hoisted.
class Ninja {
// This is where you define your constructor method.
constructor(name,health,speed,strengh){
this.name = name;
this.health = health;
this.speed = speed;
this.strength = strength;
}
sayName() {
console.log(`Hello my name is ${this.name}`);
}
showStats(){
console.log(`Name: ${this.name}\nSpeed: ${this.speed}\nStrength:
${this.strength}\nHealth: ${this.health}`);
}
drinkSake(){
this.health += 10;
}
}
// Make instances of the class down yonder below the class
// This is calling the constructor method.
const benny = new Ninja("Benny Bob",100,3,3);
// You can also call the methods on the class
benny.showStats();
// Should output
// Name: Benny Bob
// Speed: 3
// Strength: 3
// Health: 100
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。