在 JavaScript 中模拟结构体
Harshit Jindal
2023年10月12日

本教程介绍了如何在 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
第一种方法更像是一个结构体工厂,我们可以创建任意数量的副本,但是在对象文字的情况下,我们必须再次编写完整的声明。
作者: Harshit Jindal
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