简体   繁体   English

在 JS OOP 中创建一个类

[英]Creating a class in JS OOP

Can You help with this thing that I need to figure out.你能帮我解决这个我需要弄清楚的事情吗? I started learning Js with OOP but I am kind of stuck with this, where am I making a mistake.我开始用 OOP 学习 Js,但我有点坚持这个,我在哪里犯了错误。 This is the assignment I have to figure out这是我必须弄清楚的任务

Create a class Car with a property that holds a number of doors and one method that prints the number of doors to the console.创建一个 Car 类,它的属性包含门的数量和一个将门的数量打印到控制台的方法。

class Car { 
    constructor(doors){
     this.doors=doors
     console.log(doors)
    }
}

you need to create a method in the Car class to print the number of doors and then you need to instantiate the class with a given number of door & then call that method on it.您需要在 Car 类中创建一个方法来打印门的数量,然后您需要使用给定数量的门实例化该类,然后在其上调用该方法。

class Car { 
    constructor(doors){
     this.doors = doors;
    }
    print(){
        console.log(this.doors);
    }
}

const bmw = new Car(4);
bmw.print()

Hey 👋嘿👋

Yeah no problem :)是的没问题:)

class Car {
    constructor(doors) {
        this.doors = doors;
    }

    printDoors() {
        console.log(this.doors);
    }
}

In JS OOP you have to define your member variables within the constructor by using the this keyword.在 JS OOP 中,您必须使用this关键字在构造函数中定义成员变量。 To access your variables somewhere else in the class you also have to use `this.要访问类中其他地方的变量,您还必须使用`this。

The printDoor() function has to be defined at its own to call it later on like this: printDoor()函数必须自己定义,以便稍后像这样调用它:

const numberDoors = 4;
const myCar = new Car(numberDoors);
myCar.printDoors();
// expected output: 4

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

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