ctrlmaniac
ctrlmaniac

Reputation: 444

Is it possible to invoke a function outside the "parent" function?

I wondered if it was possible to invoke a function outside its "parent" function:

var $element = $( '.element' );

function myFunction( element ) {
    var width;

    function onResize() {
        width = element.width();
    }
    onResize();
}

$( window ).resize(function() {
    onResize();
});

The console returns: Uncaught ReferenceError: onResize is not defined I thought it was possible to define it outside the function as for variables:

var variable;

$( window ).resize() {
    variable = 1;
});
$( window ).resize();

how can I define it also outside the main function?

Upvotes: 0

Views: 251

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074585

Symbols declared within a function are scoped to that function (and any nested functions), so they're not accessible from outside of that function, not least because, since each call to the function creates a new version of those symbols' values, using one outside of the function would raise the question of which one to use.

But functions are objects, and so you can get references to them, and if you can get references to them you can call them. The usual way you'd get a reference to the onResize created by a specific call to MyFunction would be to use it from code within the MyFunction, or for MyFunction to return a reference to the onResize created by that call to it:

function myFunction( element ) {
    var width;

    function onResize() {
        width = element.width();
    }
    onResize();

    return onResize;
}

$(window).resize(MyFunction());

Upvotes: 3

Related Questions