Javascript 如何从字符串创建名为的类方法?
这是否可能在JS中有一个类并从字符串中声明两个方法名? 我的意思是这样的: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的类。我需要创建一些函数,它们的
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
。非常感谢。