[英]How to add getter with string method inside an object
I have an object called headers.我有一个名为 headers 的 object。 Inside which I want to add certain headers with some random value like:
在其中我想添加一些带有一些随机值的标题,例如:
configs = {
header : {
'x-some-id': Math.random().toString()
}
}
The config paramter is used to client which is used to send http requests.配置参数用于客户端,用于发送 http 请求。 And the randomid is some id generated by a load balancer.
randomid 是由负载均衡器生成的一些 id。 So it will we different for every request.
所以我们会根据每个请求而有所不同。 We dont want to create a new client for every client, hence I want to use getter function in header so that everytime a request is made, the header is automatically populated with a new id.
我们不想为每个客户端创建一个新客户端,因此我想在 header 中使用 getter function,这样每次发出请求时,header 都会自动填充一个新 ID。 How do I implement this using getters.
我如何使用 getter 实现它。 ideally this is what I what to achieve:
理想情况下,这就是我要实现的目标:
configs = {
header : {
'x-some-id': get() { return Math.random().toString()}
}
}
The syntax for getters is getter 的语法是
configs = {
header: {
get 'x-some-id'() { return Math.random().toString(); },
},
};
Not sure if that's what you wanted but you can use a Proxy
不确定这是否是您想要的,但您可以使用
Proxy
const configs = { header: new Proxy({ }, { get() { return (Math.random() * 1000000 | 0).toString() } }) } console.log(configs.header['x-some-id'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.