nic*_*ckf 99 javascript struct
以前,当我需要存储一些相关变量时,我会创建一个类.
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')
];
Run Code Online (Sandbox Code Playgroud)
但我想知道这是不是一个好习惯.还有其他更好的方法来模拟Javascript中的结构吗?
Mar*_*rot 170
对象文字和构造对象之间的唯一区别是从原型继承的属性.
var o = {
'a': 3, 'b': 4,
'doStuff': function() {
alert(this.a + this.b);
}
};
o.doStuff(); // displays: 7
Run Code Online (Sandbox Code Playgroud)
你可以做一个结构工厂.
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
Run Code Online (Sandbox Code Playgroud)
vav*_*ava 26
我总是使用对象文字
{id: 1, speaker:"john", country: "au"}
Run Code Online (Sandbox Code Playgroud)
Mar*_*rio 16
真正的问题是语言中的结构应该是值类型而不是引用类型.建议的答案建议使用对象(它们是引用类型)代替结构.虽然这可以达到其目的,但它回避了程序员实际上想要使用值类型(如原语)代替引用类型的好处这一点.例如,值类型不应导致内存泄漏.
按照 Markus 的回答,在较新版本的 JS(我认为是 ES6)中,您可以更简单地使用箭头函数和Rest 参数创建一个“结构”工厂,如下所示:
const Struct = (...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {}))
const Item = Struct('id', 'speaker', 'country')
var myItems = [
Item(1, 'john', 'au'),
Item(2, 'mary', 'us')
];
console.log(myItems);
console.log(myItems[0].id);
console.log(myItems[0].speaker);
console.log(myItems[0].country);
Run Code Online (Sandbox Code Playgroud)
运行结果如下:
[ { id: 1, speaker: 'john', country: 'au' },
{ id: 2, speaker: 'mary', country: 'us' } ]
1
john
au
Run Code Online (Sandbox Code Playgroud)
你可以让它看起来类似于 Python 的 namedtuple:
const NamedStruct = (name, ...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {_name: name}))
const Item = NamedStruct('Item', 'id', 'speaker', 'country')
var myItems = [
Item(1, 'john', 'au'),
Item(2, 'mary', 'us')
];
console.log(myItems);
console.log(myItems[0].id);
console.log(myItems[0].speaker);
console.log(myItems[0].country);
Run Code Online (Sandbox Code Playgroud)
结果:
[ { _name: 'Item', id: 1, speaker: 'john', country: 'au' },
{ _name: 'Item', id: 2, speaker: 'mary', country: 'us' } ]
1
john
au
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
155755 次 |
最近记录: |