简体   繁体   English

使用动态值在对象中设置值

[英]Set value in the object with dynamic value

First, here is my code: 首先,这是我的代码:

var lastUsedId = '';
var object = {
    element: lastElement()
};

function lastElement() {
    return lastUsedId;
}

lastUsedId = 123;

console.log(object); // returns `{element: ""}` and should `{element: 123}`

As you can see, I have defined object with key element which should contain last used element's ID. 如您所见,我用键element定义了对象,该element应包含最后使用的元素的ID。 Problem is that I don't know that ID yet it comes to print the result. 问题是我还不知道ID是否可以打印结果。 I can't change the value like object.element = 123 because of my robust application, so don't send comments like that. 由于我的应用程序功能强大,因此无法更改诸如object.element = 123类的值,因此请勿发送此类注释。 For this question, it has to bee structured like that. 对于这个问题,它必须像这样结构。

My question is: can I set the value like function, which returns the variable with content changed afterward? 我的问题是:我可以设置函数之类的值,该函数返回变量后其内容已更改吗? Maybe it is stupid question, but when it is not possible just say it and I will try to find other way. 也许这是一个愚蠢的问题,但是当不可能时,只需说一遍,我将尝试寻找其他方法。

Not sure this is what you want, but you can use a getter for that: 不确定这是否是您想要的,但是您可以为此使用getter

 var lastUsedId = ''; var object = { get element() { return lastElement() } }; function lastElement() { return lastUsedId; } lastUsedId = 123; console.log(object); lastUsedId = 456; console.log(object); 

can I set the value like function, which returns the variable with content changed afterward? 可以设置类似函数的值,该函数返回变量,其内容随后会更改吗?

Why not keep the value as a function only 为什么不将值仅保留为function

var obj = {
    element: lastElement
};
console.log( obj.element() ); //this will invoke the method to get the latest value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM