我会尽量说清楚。我在 Javascript 中有一个 DVD 对象。它具有分配给它的一小部分属性。我希望能够通过传递属性的名称而不是为每个不同的属性设置一个函数来更改它们的值,但我似乎无法完成它而且我很确定这是因为我不是足够熟悉 eval() 函数。
这是我使用的代码:
function DVDItem()
{
var Properties = {
DVDShortName: "",
HasActivationKey: true,
NetInstFolderName: "",
AddTitlesCheck: true,
LocalTestCheck: true, }
this.updateProperty = function(propertyName, propertyValue)
{
var specificProperty = eval("Properties." + propertyName);
specificProperty = propertyValue;
}
}
这样我就可以声明一个对象并更改它的属性:
var DVD1 = new DVDItem();
DVD1.updateProperty("HasActivationkey", false);
但我没有做正确的事情,因为这不起作用。 有什么想法吗?
谢谢
最佳答案
试试这个:
function DVDItem() {
var Properties = {
DVDShortName: "",
HasActivationKey: true,
NetInstFolderName: "",
AddTitlesCheck: true,
LocalTestCheck: true,
}
this.updateProperty = function(propertyName, propertyValue) {
Properties[propertyName] = propertyValue;
}
}
常见的约定是让 getter 和 setter 函数相同,如下所示:
function DVDItem() {
var attrs = {
DVDShortName: "",
HasActivationKey: true,
NetInstFolderName: "",
AddTitlesCheck: true,
LocalTestCheck: true
}
this.attr = function(key, value) {
if(value !== undefined){
return this.attrs[key] = value;
}else{
return this.attrs[key];
}
}
}
至于 eval()
,这是来自 MDN 文档的:
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.
eval() is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
There are safe (and fast!) alternatives to eval() for common use-cases.
阅读更多 here .
关于javascript - 无法通过 eval() 函数更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23018354/