我有一个泛型函数,它可以在适当的对象中调用多个其他函数,是否可以使用字符串来调用适当的函数。
var string = "save";
var generic = (new function (string) {
string."alert()";
return this;
})
var save = (new function (string) {
this.alert = (function () {
alert("your document has been saved")
return this
})
return this
})
var notSaved = (new function (string) {
this.alert = (function () {
alert("your document has not been saved")
return this
})
return this
})我将它用于更复杂的设置,但这里有一个示例。这个是可能的吗?
发布于 2011-11-05 14:36:18
您可以将您的函数包含在某个对象中,这样您就可以通过使用某个变量(在本例中名为string)传递属性名称来进行访问,例如。就像这样:
var string = 'notSaved';
var funcs = {};
funcs.save = new function(){
this.alert = function(){
alert('called save.alert()');
};
return this;
};
funcs.notSaved = new function(){
this.alert = function(){
alert('called notSaved.alert()');
};
return this;
};
funcs[string].alert();参见working example on jsfiddle。
如果您的变量是全局对象(不应该是全局变量),它们也会自动包含在window对象中,所以您也可以像这样调用它们:window[string].alert()。这对非全局函数不起作用(在这种情况下,我的解决方案似乎是唯一不使用eval()的)。
发布于 2011-11-05 14:30:11
你当然可以。尝试如下所示:
window[string].alert();发布于 2011-11-05 15:16:26
看看你的代码,很难知道你真正想要实现的是什么。尽管如此,这里有一些可能相关的想法。
首先,让我们创建几个对象:
var rabbit = {
name: 'Peter',
hop: function () {
return this.name + ' hopped!'
},
jump: function () {
return this.name + ' jumped!'
}
}
var hairy_maclary = {
name: 'Hairy Maclary',
jump: function () {
return this.name + ' jumped over the fence!'
}
}现在,您可以定义一个函数,该函数对传递给它的任何对象调用hop方法:
function hop(object) {
return object.hop()
}
hop(rabbit) // 'Peter hopped!'我不确定为什么您要这样做而不是直接调用hop,但是您可能想要在之前或之后做一些额外的事情。
如果您愿意,您可以创建一个完全泛型函数,该函数将调用给定对象上的给定方法:
function invokeMethod(object, method) {
object[method]()
}
invokeMethod(hairy_maclary, 'jump') // 'Hairy Maclary jumped over the fence!'然而,想要做这件事真的很奇怪。也许您可以提供更多关于您实际尝试做什么的想法,因为您的示例代码相当奇怪。
https://stackoverflow.com/questions/8018559
复制相似问题