JavaScript에서 구조체 시뮬레이션

JavaScript에서 구조체 시뮬레이션

이 튜토리얼에서는 JavaScript에서 구조체를 시뮬레이션하는 방법을 소개합니다. JavaScript에서 모든 함수는 객체이며 속성이나 변수를 연결할 수 있습니다. 따라서 함수를 선언하고 다양한 속성을 추가하여 구조체를 시뮬레이션 할 수 있습니다.

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  ')
];

또는 객체 리터럴을 사용할 수도 있지만 객체에 연결된 모든 속성을 볼 수 없거나 C의 구조체와 같이 기본적으로 모든 요소에 대한 공통 구조를 가질 수 없습니다.

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

첫 번째 접근 방식은struct팩토리와 비슷합니다. 원하는만큼 사본을 만들 수 있지만 객체 리터럴의 경우 완전한 선언을 다시 작성해야합니다.

튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
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