[英]Javascript window[“functionName”](arguments) returns “is not a function” TypeError
[英]Uncaught TypeError: is not a function when using window[functionName]
我在这里找到有关从字符串调用函数的页面 。 底部有一个更新,指出最好使用window[functionName](params)
,并给出以下示例:
var strFun = "someFunction";
var strParam = "this is the parameter";
//Create the function
var fn = window[strFun];
//Call the function
fn(strParam);
所以,我这样写:
var OnChange = function( e )
{
var oContainer = _.DOM.GetElementByAttribute( document, 'data-instance', _testInstance );
var evt = ( e ) ? e : window.event;
var objects = GetObjects( oContainer );
var files = [];
if( evt.target.files ) // html5 .. multiple?
{
for( var i = 0; i < evt.target.files.length; i++ )
files.push( evt.target.files[i].name ); // + " (" + Format.Size( evt.target.files[i].size ) + ")" );
}
else
{
files.push( evt.target.value );
}
var strFunc = "User.UploadPicture";
var test = window[strFunc];
test(e); // error
};
我收到以下错误:
未捕获的TypeError:test不是函数
User.Upload
是js文件中的函数。 我想念什么吗?
假设User
是一个包含函数UploadPicture
的全局范围对象,则需要这样调用它:
var test = window["User"]["UploadPicture"];
test(e);
window["User.UploadPicture"]
指的是在window
对象上称为“ User.UploadPicture”的属性,与User
对象无关。
但是,在这种情况下,您链接到的页面似乎是在谈论调用要在运行时确定名称的函数。 如果您始终要调用User.UploadPicture
,则直接调用它没有错:
User.UploadPicture(e);
如果您在编写代码时不知道名称,则只需要使用其他方法,而是想在运行时动态调用不同的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.