I am learning Javascript.
I think there are several ways to write, but the general way to write is
Which of the following two types is the mainstream?(Is there any other way to write?)
Also, are there any advantages or disadvantages of each writing method?
The writing style varies depending on the site, and for beginners
I don't know which way to write at first.
Thank you for your cooperation.
function animal1(name,age,sex){
this.name=name,
this.age=age,
this.sex=sex,
This.getName=function(){
console.log(name);
},
This.getAge=function(){
console.log(age);
}
This.getSex=function(){
console.log(sex);
}
};
varanimal2=function(name,age,sex){
this.name=name,
this.age=age,
this.sex=sex,
This.getName=function(){
console.log(name);
},
This.getAge=function(){
console.log(age);
}
This.getSex=function(){
console.log(sex);
}
};
vartama = new animal 1("tama", 13, "female");
tama.getName();
varmike = new animal 2 ("mike", 11, "male");
Mike.getName();
Benefits of the former function declaration
vartama=new animal1("tama", 13, "female");
function animal1(name,age,sex){
...
}
Benefits of the latter functional expression
//Defining the namespace com.example.zoo
constcom={};
com.example={};
com.example.zoo={};
// Define anim2 in the namespace com.example.zoo
com.example.zoo.animal2=function(name,age,sex){...};
// instantiation
let mike = new com.example.zoo.animal2(...);
Based on the above, doesn't make much difference, so you can choose whichever you like.I think I see the former more often, but it's just my personal impression.
If the situation permits, I have the impression that the class syntax is preferred these days.
class animal3 {
constructor(name,age,sex){
this.name = name;
This.age=age;
this.sex =sex;
}
getName(){
console.log (this.name);
}
getAge(){
console.log(this.age);
}
getSex(){
console.log(this.sex);
}
}
© 2024 OneMinuteCode. All rights reserved.