javascript - 无法通过 eval() 函数更新变量

标签 javascript oop

我会尽量说清楚。我在 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/

相关文章:

javascript - 有没有办法制作prezi然后以某种方式将其转换为html和css类型代码

Javascript:将 undefined variable 传递给函数

javascript - 你可以在 pug 文件中使用 PHP 吗?

oop - 我为什么要使用接口(interface)?

C++ 对象列表不能正常工作

c++ - 与 friend 在类里面隐藏公共(public)细节的内部功能

javascript - 计算服务调用收集响应所需的时间

JavaScript 替换()正则表达式 : nesting modifier

c++ - 什么样的 OOP 设计决策适合客户端/服务器应用程序中的协议(protocol)情况?

javascript - 尽管使用有效参数调用,但设置方法未设置成员