0

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.

2
  • 2
    This is possible and its already working for you. What is your question then? Commented Jul 17, 2014 at 11:12
  • @RahilWazir Thank you, sorry I forgot to add 'new' and had: var c = MyClass(); It is indeed working with new MyClass. Thank you! Commented Jul 17, 2014 at 11:27

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.