DEV Community

ana
ana

Posted on

javaScript Class

Image description

In this article I just want explain a little about class topic in java script.
As you know Class its a concept that you can see in any programming language.
letsGo...
In first I show you syntax of class:

class ClassName{
constructor(){...}
}
Enter fullscreen mode Exit fullscreen mode

Tip/ normally we write class name with capital letter.

Here there is 1 question! what is constructor?
actually the constructor is a place that we declare all variable we want use in our class, in every function we make it later, for example:

class Human{
constructor(name, lName, age){
this.name = name;
this.lName = lName; 
this.age = age;
}
...
}
Enter fullscreen mode Exit fullscreen mode

as you can see in above codes I declare All variables in constructor. just for you know, the constructor in JS is __init__ in python.

well it doesn't matter. anyway, after make your constructor maybe you want to use from those in your functions..
if I want show this in example:

class Human{
constructor(name, lName, age){
this.name = name;
this.lName = lName; 
this.age = age;
}
showName(){
console.log(this.name + " " + this.lName);
}
}
Enter fullscreen mode Exit fullscreen mode

Tip1/ showName is a function.
Tip2/ this keyword refers to variable we declare in our class and you should use from that.

so How can we use from our Class?

const VariableName = new ClassName(parameter1, parameter2,...)
Enter fullscreen mode Exit fullscreen mode

in example:

const person1  = new Human("Ana", "am", "19");
Enter fullscreen mode Exit fullscreen mode

Tip1/ order for declare value is important. if i Write "19" at the first that value it will equal to name.

How can we use from our Function? (showName)

person1.showName();
Enter fullscreen mode Exit fullscreen mode

I should tell you, in this subject(class) there are so many tips. and you should care about this and learn more about it. I just explained the class topic in really short form.

Don't forget practice.

Top comments (2)

Collapse
 
gilfewster profile image
Gil Fewster

There’s a bug in your code.

this.lName = age; should be this.lName = lname;

Collapse
 
anateotfw profile image
ana

🙃thanks.