从事面向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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...