如何从字符串创建一个名称的类方法

How to create a class method with name from string?

本文关键字:一个 类方法 字符串 创建      更新时间:2023-09-26

是否可以在JS中有一个类并从字符串中声明2个方法名称?我的意思是这样的:

function MyClass()
{
var methods = ['hello', 'hey'];
for (var i in methods)
{
    this[methods[i]] = function()
    {
       alert('This is method ' + methods[i]);
    }
}
}

这将创建一个带有hello和hey函数的类。我需要创建一些功能,其中有非常相似的身体,但不同的名称。我不想使用eval,所以代码可以被编译。

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css"></link>
    </head>
    <body>
        <script>
function generator(i) {
    return function (x) {
        return x * i;
    }
}
function foo(methods) {
    var i;
    for (i = 0; i < methods.length; i++) {
        this[methods[i]] = generator(i);
    }
}
var test = new foo(['nulify', 'repeat', 'double']);
console.log(test.nulify(10));
console.log(test.repeat(10));
console.log(test.double(10));
        </script>
    </body>
</html>

更多问题…