Tôi đã làm việc về vấn đề này, vì tôi cần một chức năng như thế này. Đây là mã sandbox của tôi, không được kiểm tra kỹ lưỡng, nhưng có thể là điểm khởi đầu cho những người khác. Lưu ý rằng có một eval() trong mã như tôi không thể tìm ra cách bỏ qua bước đó, có thể là một javascript quirk và không thể được thực hiện theo bất kỳ cách nào khác. Hãy cho tôi biết nếu có cách nào để loại bỏ eval() ở đây!
executeFunctionByName = function(functionName)
{
var args = Array.prototype.slice.call(arguments).splice(1);
//debug
console.log('args:', args);
var namespaces = functionName.split(".");
//debug
console.log('namespaces:', namespaces);
var func = namespaces.pop();
//debug
console.log('func:', func);
ns = namespaces.join('.');
//debug
console.log('namespace:', ns);
if(ns == '')
{
ns = 'window';
}
ns = eval(ns);
//debug
console.log('evaled namespace:', ns);
return ns[func].apply(ns, args);
}
core = {
paragraph: {
titlebar: {
user: "ddd",
getUser: function(name)
{
this.user = name;
return this.user;
}
}
}
}
var testf = function()
{
alert('dkdkdkd');
}
var x = executeFunctionByName('core.paragraph.titlebar.getUser', 'Ikon');
executeFunctionByName('testf');
thể trùng lặp của [Làm thế nào để thực hiện một Hàm JavaScript khi tôi có tên của nó dưới dạng một chuỗi] (http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a- chuỗi) – olibre