简体   繁体   English

检查javascript函数是否存在变量并执行

[英]Check if javascript function exist with variable and execute it

I have a popup system in my project. 我的项目中有一个弹出系统。 With a name, for example 'addnews', it knows which popup content to add and which script is necessary to handle the form. 使用名称(例如“ addnews”),它知道要添加的弹出内容以及处理表单所需的脚本。 Up until now after completion I always did the same thing. 到目前为止,完成后我一直都做同样的事情。 Now, in some cases, I want to do something different. 现在,在某些情况下,我想做些不同的事情。

Now I want to add a JavaScript function with that same name, like previous example 'addnews()', and check if that function exist. 现在,我想添加一个具有相同名称的JavaScript函数,例如前面的示例“ addnews()”,并检查该函数是否存在。 If it does run it, else do the standard things. 如果运行,则执行标准操作。 (1) (1)

Also executing a function with that name as variable doesn't seem to work. 同样执行以该名称作为变量的函数似乎也不起作用。 (2) (2)

var functionName = 'addnews';

if (typeof functionName == 'function') { // (1) typeof functionName = string
    window[functionName](); // (2) this doesn't work for me
} else {
    // Do something standard
}

function addnews() {
    // Do something special
}

If you use this code in a document and it is not loaded complitelly your code will not find the function addnews() because it is not declare before this code. 如果您在文档中使用此代码并且没有被强制加载,那么您的代码将找不到addnews()函数,因为该函数未在此代码之前声明。

Like in the comments: you need to use 就像在评论中一样:您需要使用

if (typeof window[functionName] == 'function') 

This will do it: 这样做:

if (typeof eval(functionName) == 'function') { 
    eval(functionName+'()');
} else {
    // Do something standard
}

Update: Only use this if the answer of Mic doesnt work (whyever). 更新:仅当麦克风的答案无效时才使用此功能(但是)。 Like he said eval is pretty dangerous. 就像他说的,评估非常危险。

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

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