Which is the main way to write objects in Javascript?

Asked 1 years ago, Updated 1 years ago, 21 views

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();

javascript

2022-09-30 16:01

1 Answers

Benefits of the former function declaration

  • Simplified code than functional expressions
  • On the source, you can write a code to call a function above the function declaration
vartama=new animal1("tama", 13, "female");
function animal1(name,age,sex){
  ...
}

Benefits of the latter functional expression

  • The only way to write a class of methods is to use a functional expression, and the constructor is more consistent with a functional expression.
  • To put a function in the namespace, the function expression is simpler because function declarations take twice.
//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);
  }
}


2022-09-30 16:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.