[英]Get Result of New Function to variable
我做了以下似乎是錯誤的邏輯
function test() { return 'hello'; } function getFn(whichFn) { var Fn = new Function(whichFn); return (Fn()); } var testResult = getFn('test()'); console.log(testResult);
我期待'hello'的輸出,但我得到了未定義
使用return window[whichFn].call();
相反,不要將函數調用括號傳遞給getFn
:
function test() { return 'hello'; } function getFn(whichFn) { return window[whichFn].call(); } var testResult = getFn('test'); console.log(testResult);
'test()'
你的函數沒有return
語句,所以它總是返回undefined
。
function test() { return 'hello'; } function getFn(whichFn) { var Fn = new Function(whichFn); return (Fn()); } var testResult = getFn('return test()'); console.log(testResult);
不要這樣做。 從字符串生成函數幾乎總是解決用閉包或變量更好地解決的問題的解決方案:
function test() { return 'hello'; } function getFn(whichFn) { return window[whichFn](); } var testResult = getFn('test'); console.log(testResult);
嘗試這個
function test() { return 'hello'; } function getFn(whichFn) { var Fn = new Function(whichFn); return (Fn()); } var testResult = getFn('return test()'); console.log(testResult);
@killair 嘿伙計,我繼續將其重新修改為 ES6
const test = () => {
return 'it works';
}
const getFn = (whichFn) => {
return whichFn();
}
var testResult = getFn(test);
console.log(testResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.