JavaScript的自定义索引访问 [英] Javascript custom index accessor
问题描述
在C#中,您可以创建像这样一个自定义的索引
In c# you can create a custom indexer like so
public object this[string name]
{
}
我与它有一个小部件,需要对象的阿雷作为属性称为标签,像这样一个JavaScript控件库工作
I'm working with a javascript widget library which has a widget that takes an aray of objects as a property called labels like so
new Thingy({
labels: [{value:1, text:"my label"},[{value:2, text:"my next label"}]
});
问题是,你必须提前计划确切地知道所有值都将需要一个标签。例如,在上面的例子中,我知道该标签将是值1和2。但是,如果我不知道是什么值可能是,我想能够基于价值它动态地创建文本尝试访问
The problem is that you have to plan ahead to know exactly what all the values are that will need a label. For instance, in the example above, i know that the labels will be for values 1 and 2. But if I don't know what the values might be, i would like to be able to dynamicly create the text based on the value it tries to access
所以当库内部尝试访问:
so when the library internally tries to access:
this.labels[n].text
我想this.labels [N]做这样的事情。
I would like this.labels[n] to do something like
function(n){return {text: "label for " + n};}
这是可能的JavaScript语言的范围内?
Is this possible within the bounds of the javascript language?
推荐答案
您可以得到的 ES6代理在最新的Chrome和编写一个处理像在C#中,但它不会与旧的浏览器兼容。
You can get es6 proxies in latest Chrome and write a handler like in C#, but it won't be compatible with older browsers.
同时,我建议把一个 getLabel()
方法在 Thingy.prototype
。
Meanwhile I suggest putting a getLabel()
method on a Thingy.prototype
.
这篇关于JavaScript的自定义索引访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!