Help with nested Javascript functions

3

I have a page that loads a Javascript and contains this:

(function(f) {
    function qb(a) {
        var b = g.sockets[a];
        b.onopen = b.onclose = b.onmessage = b.onerror = function() {};
        for (var d = 0; d < b.events.length; ++d) U(b.events[d][1]);
        b.events = null;
        try {
            b.close()
        } catch (t) {}
        g.sockets[a] = null
    }

    function tb(a) {
        eval.call(null, a)
    }

})

I would like to know how I call the tb function from the chrome console because I get the following error VM3784: 1 Uncaught ReferenceError: tb is not defined (...)

    
asked by jony alton 06.12.2016 в 21:35
source

3 answers

3

Good, you can not, because it is inside a function anonymous , you can only see the debug (F12 in browser to remove the console) and put a breakpoint inside.

You have a nested function inside another, these functions usually take the name of inner-private, they are inner because they are internal and private because they are only accessible from the code of the function.

I leave a page for you to understand it better.

link

answered by 06.12.2016 в 22:20
3

As said @ sakulino, without modifying the code, it is not possible unless you do some eval () hack with the script. If you can modify it, the ideal will be that you expose the internal functions:

var f = (function(f) {
    function qb(a) {
        var b = g.sockets[a];
        b.onopen = b.onclose = b.onmessage = b.onerror = function() {};
        for (var d = 0; d < b.events.length; ++d) U(b.events[d][1]);
        b.events = null;
        try {
            b.close()
        } catch (t) {}
        g.sockets[a] = null
    }

    function tb(a) {
        eval.call(null, a)
    }
    return {
        qb: qb,
        tb: tb
    }
})();

f.gb();
f.tb();
    
answered by 07.12.2016 в 00:06
1

I recommend that you work as little as possible with anonymous functions. It is true that they provide a lot of comfort when it comes to work, but they can become a problem. It is a bit more "docile" if you have an object, which you can treat with more flexibility. In the case of your code, you simply do not need to use nested functions. For example:

function qb(a) {
    var b = g.sockets[a];
    b.onopen = b.onclose = b.onmessage = b.onerror = function() {};
    for (var d = 0; d < b.events.length; ++d) U(b.events[d][1]);
    b.events = null;
    try {
        b.close()
    } catch (t) {}
    g.sockets[a] = null
}

function tb(a) {
    eval.call(null, a)
}

I think it would not be necessary to declare functions within functions, if they are not going to work directly with the internal data of the most external function.

    
answered by 07.12.2016 в 06:37