0

I`m trying to build an function that load script on-demand. That is my current code:

function loadScript(src, name = null)
{
    var dfd = jQuery.Deferred();

    if (name === null) {
        name = src.split(/\\|\//); // split by folder separator 
        name = name[(name.length - 1)].split('.'); // catch last index & split by extension 
        name.splice(name.length - 1, 1) // Remove last
        name = name.join('.'); // add points in the middle of file name
    }

    if ( typeof name === 'function' ) return dfd.promise().resolve(name);

    $.getScript( src )
    .done(function( script, textStatus ) {
        dfd.resolve(name);
    })
    .fail(function( jqxhr, settings, exception ) {
        dfd.reject(exception);
    });

    return dfd.promise();
}

My problem is on this part of code:

if ( typeof name === 'function' ) return dfd.promise().resolve(name);

Where name is a variable that contains desired function name to check, but not the real function name, causing function never evaluate as 'function'.

I tried:

typeof `${name}` // resulting a "string" 

eval("typeof name === 'function'") // But my node system not accept eval due to a potentially security risk

How many alternatives that I have ?

3 Answers3

0

You could do typeof eval(name) === function or if the function is a global, typeof window[name] === function

Demo:

(function() {
    function test() {}
    (function(name) {
        console.log(typeof eval(name) === 'function');
    })('test');
})();
Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • As I said, eval() is not an alternative – Bruno Natali Mar 24 '20 at 22:27
  • Ok I read too fast, then it's not possible unless it's a global function, or unless it's attached to a particular object, is it? – Guerric P Mar 24 '20 at 22:29
  • I really do not know, I dynamically load script with Jquery getScript. This script contains classes or Functions. To prevent re-declare a function, this if need to evaluate and prevent script to load again. – Bruno Natali Mar 24 '20 at 22:41
  • Ok then the function you're looking for must be global. Did you try `typeof window[name] === function`? – Guerric P Mar 24 '20 at 22:43
0

Quick and dirty:

if ( typeof name === 'string' && typeof eval(name) === 'function' ) return dfd.promise().resolve(name);

since you probably want to double-check that name is actually a before passing it to eval. You probably also want to further validate it if it's coming from user input as you could be opening yourself up to script injections.

0

Hope this could helps anyone;

const getFunc = (s) => {
   const a = s.split(".");
   let obj = window, i = 0;
   while (i < a.length && (obj = obj[a[i++]]) !== undefined);
   if (typeof obj === "function") return obj;
};

console.log(getFunc("Infinity.isFloat"));
OO7
  • 660
  • 4
  • 10