简体   繁体   中英

Uncaught TypeError: is not a function when using window[functionName]

I found this page here about calling a function from a string. At the bottom there's an update that states it's better to use window[functionName](params) , and gives this example:

var strFun = "someFunction";
var strParam = "this is the parameter";

//Create the function
var fn = window[strFun];

//Call the function
fn(strParam);

So, I wrote this:

  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
  };

And I'm getting the following error:

Uncaught TypeError: test is not a function

User.Upload is a function inside the js file. Am I missing something?

Assuming that User is a globally scoped object containing a function UploadPicture , you would need to call it like this:

var test = window["User"]["UploadPicture"];
test(e);

window["User.UploadPicture"] refers to a property called, literally, "User.UploadPicture" on the window object, and is nothing to do with the User object.

In this instance however, the page you've linked to seems to be talking about calling a function that you'll determine the name of at runtime. If, in your case, you're always going to call User.UploadPicture , there's nothing wrong with calling it directly:

User.UploadPicture(e);

You only need to use the other methods if you don't know the name when you're writing the code , and instead want to dynamically invoke different functions at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM