Javascript 中的结构体 [英] Structs in Javascript

查看:170
本文介绍了Javascript 中的结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,当我需要存储大量相关变量时,我会创建一个类.

Previously, when I needed to store a number of related variables, I'd create a class.

function Item(id, speaker, country) {
    this.id = id;
    this.speaker = spkr;
    this.country = country;
}
var myItems = [
    new Item(1, 'john', 'au'),
    new Item(2, 'mary', 'us')
];

但我想知道这是否是一个好习惯.还有其他更好的方法可以在 Javascript 中模拟结构吗?

But I'm wondering if this is a good practice. Are there any other, better ways to simulate a struct in Javascript?

推荐答案

对象字面量和构造对象之间的唯一区别是从原型继承的属性.

The only difference between object literals and constructed objects are the properties inherited from the prototype.

var o = {
  'a': 3, 'b': 4,
  'doStuff': function() {
    alert(this.a + this.b);
  }
};
o.doStuff(); // displays: 7

<小时>

你可以创建一个结构工厂.


You could make a struct factory.

function makeStruct(names) {
  var names = names.split(' ');
  var count = names.length;
  function constructor() {
    for (var i = 0; i < count; i++) {
      this[names[i]] = arguments[i];
    }
  }
  return constructor;
}

var Item = makeStruct("id speaker country");
var row = new Item(1, 'john', 'au');
alert(row.speaker); // displays: john

这篇关于Javascript 中的结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆