2016-09-11 35 views
-3

我需要通過var字符串調用函數。我看到這個問題之前已被問到: How to execute a JavaScript function when I have its name as a string當我的名字爲字符串時執行JavaScript函數 - 不工作

但是解決方案不起作用。我做錯什麼了嗎? https://jsfiddle.net/puLh9keg/

// a.callThis is the function that will be called using var string 
var a = { 
    callThis: 
    function (ok, param1, param2) { 
      alert(ok + "|" + param1 + "|" + param2); 
     } 
} 

// Below is from https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string 
function executeFunctionByName(functionName, context /*, args */) { 
    var args = [].slice.call(arguments).splice(2); 
    var namespaces = functionName.split("."); 
    var func = namespaces.pop(); 
    for(var i = 0; i < namespaces.length; i++) { 
    context = context[namespaces[i]]; 
    } 
    return context[func].apply(context, args); 
} 


// try call a.callThis by var string 
var fn = 'a.callThis'; 
executeFunctionByName(fn, window, true, 'param1', 'param2'); 
+2

請告訴我們您的意思是 「不工作」。 –

+1

看看你的代碼是如何被添加到結果窗口中的(使用開發工具),你會發現你並沒有使用正確的JSFiddle設置來完成這個工作 –

+2

你的'var a'不在全局範圍內 - 改爲'window.a =' - 或者確保你的JS沒有在「負載」下運行,但是「沒有在主體中換行」或「在頭部沒有換行」 –

回答

1

你的代碼工作作爲寫。正如很多人在評論中提到的那樣,您的JSFiddle不起作用的原因是您已假設window是您運營的全球範圍。但是,您已將JSFiddle JavaScript設置爲運行onLoad。這包裝在onload處理程序中。因此,與您的假設相反,您的代碼未與作爲全局範圍的window一起運行,這使其無法工作。通過將JavaScript LOAD TYPE選項更改爲No wrap - in <head>No wrap - in <body>,可以讓您的代碼在JSFiddle上工作。

這是JSFiddle that has that change implemented

此外,下面是你的代碼片段,這是正常工作。

// a.callThis is the function that will be called using var string 
 
var a = { 
 
    callThis: 
 
    function (ok, param1, param2) { 
 
      alert(ok + "|" + param1 + "|" + param2); 
 
     } 
 
} 
 

 
// Below is from 
 
// http://stackoverflow.com/questions/359788 
 
//  /how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string 
 
function executeFunctionByName(functionName, context /*, args */) { 
 
    var args = [].slice.call(arguments).splice(2); 
 
    var namespaces = functionName.split("."); 
 
    var func = namespaces.pop(); 
 
    for(var i = 0; i < namespaces.length; i++) { 
 
    context = context[namespaces[i]]; 
 
    } 
 
    return context[func].apply(context, args); 
 
} 
 

 

 
// try call a.callThis by var string 
 
var fn = 'a.callThis'; 
 
executeFunctionByName(fn, window, true, 'param1', 'param2');

相關問題