简体   繁体   English

为 MERN 处理 Javscript OOP 项目:Class 和构造函数

[英]Working on Javscript OOP project for MERN: Class and Constuctors

I am learning about classes and constructors for MERN, and I am stuck on an algorithm.我正在学习 MERN 的类和构造函数,但我被困在算法上。

Basically, this is what I have to do: create a Ninja class add attribute: name add attribute: health add attribute speed;基本上,这就是我要做的:创建一个忍者 class 添加属性:名称添加属性:健康添加属性速度; give a default of 3;给出默认值 3; add attribute strength;.添加属性强度;。 default of 3 add method sayName();默认为 3 添加方法 sayName(); should log ninja's name add method showStats();应该记录忍者的名字 add method showStats(); should console log all stats (name, strength, speed and health) add method drinkSake();控制台应该记录所有统计数据(名称、力量、速度和健康)添加方法drinkSake(); should increase health by +10应该增加健康+10

This is my code so far:到目前为止,这是我的代码:

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;
    }
    
}

and then my constructor is listed at the bottom outside of the functions (I tried to play it inside and I also received an error然后我的构造函数列在函数之外的底部(我试图在里面播放它,我也收到了一个错误

const ninja = new Ninja ("lemon", 100){
    Ninja.sayName();
    console.log(ninja.name);
}

I am having a problem figuring out where the new instances goes.我在弄清楚新实例的去向时遇到了问题。 If you could keep the advice as basic as possible I would much appreciate it.如果你能尽可能保持基本的建议,我将不胜感激。

This is a the way you should implement the ninja class.这是您应该实现忍者 class 的方式。

    // 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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