2014-07-17 105 views
0

这是可能在JS中有一个类,并从字符串声明2个方法名? 我的意思是这样:如何用字符串的名称创建一个类方法?

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

这应该创造我一个类功能打招呼,哎。我需要创建几个非常相似但名称不同的函数。 我不想使用eval,所以可以编译代码。

+2

这是可能的,它已经为你工作。那么你的问题是什么? –

+0

@RahilWazir谢谢,对不起,我忘了添加'新',并有:'var c = MyClass();'这确实与'new MyClass'一起工作。谢谢! – Tom

回答

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> 

更多问题...

相关问题