Tom
Tom

Reputation: 3042

How to create a class method with name from string?

Is this possible to have a class in JS and declare 2 method names from string? I mean something like this:

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

This should create me a class with function hello and hey. I need to create a few functions which have very similar body but different names. I don't want to use eval, so the code can be compiled.

Upvotes: 0

Views: 70

Answers (1)

Ivan  Ivanov
Ivan Ivanov

Reputation: 2106

<!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>

More questions...

Upvotes: 2

Related Questions