Simula uno Struct in JavaScript

Simula uno Struct in JavaScript

Questo tutorial introduce come simulare una struttura in JavaScript. In JavaScript, tutte le funzioni sono oggetti e possono avere proprietà o variabili ad esse associate. Quindi, possiamo simulare una struttura dichiarando una funzione e associandovi varie proprietà.

function Movie(title, href, rating, description) {
  this.title = title;
  this.url = url;
  this.rating = rating;
  this.description = description;
}
var movies = [
  new Movie('Stuck in Love', 'stuck.in.love', '4.5', ' wefwg wr w g'),
  new Movie('Emily in Paris', 'emily.in.paris', '7.1', 'fgfdsadf ef wgf  ')
];

In alternativa, possiamo anche usare letterali oggetto, ma poi non saremo in grado di vedere tutte le proprietà associate a un oggetto o avere una struttura comune per tutti gli elementi per impostazione predefinita, come una struttura in C.

{ id: 1, speaker: 'john', country: 'au' }  // Object Literal

Il primo approccio è più simile a una fabbrica struct, possiamo creare tutte le copie che vogliamo, ma nel caso di oggetti letterali, dobbiamo scrivere di nuovo una dichiarazione completa.

Ti piacciono i nostri tutorial? Iscriviti a DelftStack su YouTube per aiutarci a creare altre guide video di alta qualità. Iscriviti
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn