【问题标题】:Is there a way to call a function inside another function?有没有办法在另一个函数中调用一个函数?
【发布时间】:2021-08-15 19:16:32
【问题描述】:

我有以下代码:


var f1 = document.getElementById("f"), 
f1 = function () {
var rd1 = new FileReader();
rd1.onload = function () {
              
             function assign () { 
                toto = function toto() {
                     // Code there
             }


        rd1.readAsBinaryString(f1.files[0]);
    }; 
f1.addEventListener('change', rd1);

我想要的是能够在上面的这个块之外调用函数 toto() 。有没有办法做到这一点或范围不允许?

【问题讨论】:

    标签: javascript file scope filereader


    【解决方案1】:

    函数声明的范围仅限于定义它们的函数。

    要在外部访问它们,您需要在某处明确分配它们。

    例如:

    let toto = null;
    
    function assign() {
         toto = function toto () { ... };
    }
    

    ...但是,除了范围之外,您正尝试在按照经典 asynchronous problem 创建它之前调用函数之前,因此您需要重新考虑您的方法。

    【讨论】:

    • 我明白了,顺便说一句,你最后如何调用 toto 函数?
    • todo()(在某个时间点之后 assign()被调用)
    • 但在我的情况下,这样做会在块内被调用,不是吗?
    • 是的(这使得在块外分配它毫无意义)。
    猜你喜欢
    • 2021-06-05
    • 2011-11-19
    • 2021-06-29
    • 1970-01-01
    • 2021-01-08
    • 2011-02-10
    • 2019-09-23
    • 2021-06-10
    • 2019-01-04
    相关资源
    最近更新 更多