[英]How it's possible to have same variable and function name in JavaScript
[英]Javascript - Variable in function name, possible?
我希望這個問題不是太簡單,但我不知道:(
如何使用函數名中的var啟動函數?
例如 ...
我的職責
function at_26();
function at_21();
function at_99();
啟動功能
var test_id = 21;
at_'+test_id+'(); // doesn't work
我希望有人可以幫助我。
提前致謝! 彼得
將您的功能存儲在對象中,而不是將它們置於頂級。
var at = {
at_26: function() { },
at_21: function() { },
at_99: function() { }
};
然后你可以像任何其他對象一樣訪問它們:
at['at_' + test_id]();
您也可以直接從window
對象訪問它們......
window['at_' + test_id]();
...並且避免將它們存儲在對象中,但這意味着要在應該避免的全局范圍內進行游戲。
你很親密
var test_id = 21
this['at_'+test_id]()
但是,你可能想要的:
at = []
at[21] = function(){ xxx for 21 xxx }
at[test_id]()
你也可以試試
function at_26(){};
function at_21(){};
function at_99(){};
var test_id = 21;
eval('at_'+test_id+'()');
但是如果您有充分的理由使用eval,請使用此代碼。 在javascript中使用eval不是一個好習慣,因為它的缺點是“使用它不正確可以打開你的腳本來注入攻擊”。
有一個更好的方法然后窗口對象 - 在firefox中不友好 - 使用“self”代替 - 所以在Quentin發布的示例中它看起來像這樣:
self['at_' + test_id]();
將一組參數傳遞給那些組合函數的示例,。
/* Store function names and match params */ let at = { at_26 : (a,b,c) => at_26(a,b,c), at_21 : (a,b,c) => at_21(a,b,c), at_99 : (a,b,c) => at_99(a,b,c), at_om : (a,b,c,d,e) => at_om(a,b,c,d,e) } /* Dynamic fuction name + array of Params */ function dynFunc(name, arrayParams){ return at[name](...arrayParams) } /* Usage examples */ dynFunc(`at_${99}`, ["track001", 32, true]) dynFunc("at_" + "om", ["track007", [50, false], 7.123, false, "Bye"]) /* Tests */ function at_99(a,b,c){ console.log("Hi! " + a,b,c) console.log(typeof(a), typeof(b), typeof(c)) } function at_om(a,b,c,d,e){ console.log("Hi! " + a,b,c,d,e) console.log(typeof(a), typeof(b), typeof(c), typeof(d), typeof(e)) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.