Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从字符串创建名为的类方法?_Javascript_Oop - Fatal编程技术网

Javascript 如何从字符串创建名为的类方法?

Javascript 如何从字符串创建名为的类方法?,javascript,oop,Javascript,Oop,这是否可能在JS中有一个类并从字符串中声明两个方法名? 我的意思是这样的: function MyClass() { var methods = ['hello', 'hey']; for (var i in methods) { this[methods[i]] = function() { alert('This is method ' + methods[i]); } } } 这将为我创建一个具有函数hello和hey的类。我需要创建一些函数,它们的

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

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>
函数发生器(一){ 返回函数(x){ 返回x*i; } } 函数foo(方法){ var i; 对于(i=0;i

更多问题…

这是可能的,它已经对您起作用了。那么你的问题是什么?@RahilWazir谢谢你,很抱歉我忘记添加“new”了:
var c=MyClass()它确实在使用
新的MyClass
。非常感谢。