简体   繁体   English

如何使用Javascript检查函数是否存在于另一个函数中

[英]How to check if function exists inside another function using Javascript

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'.其中 name 是一个变量,包含要检查的所需函数名称,但不是真正的函数名称,导致函数永远不会评估为“函数”。

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 ?我有多少选择?

You could do typeof eval(name) === function or if the function is a global, typeof window[name] === function您可以执行typeof eval(name) === function或者如果该函数是全局函数,则typeof window[name] === function

Demo:演示:

 (function() { function test() {} (function(name) { console.log(typeof eval(name) === 'function'); })('test'); })();

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.因为您可能想在将其传递给 eval 之前仔细检查该名称实际上是 a。 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.如果它来自用户输入,您可能还想进一步验证它,因为您可能会让自己接受脚本注入。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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