Jinghui Niu
Jinghui Niu

Reputation: 1140

Javascript: Are callback functions the only ones allowed to refer to outside variables in a forward-looking way?

I have the following code, note that in the callback function for the close event, the reference to the variable ConnectingLine, which comes after the callback itself:

$('.tabs').tabs({
    close: function(event, ui) {
        ConnectingLine.show();
    }
});

var ConnectingLine = MyHelpers.connectingLine({options here...});

I was assuming that this kind of referencing would work for any kind of closure, but it turns out to be not true. For example:

var add = (function () {
    return function () {return counter += 1;}
    var counter = 7;
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}

The above code would break, causing a NaN error. Apparently, the definition needs to be before the closure function referring to it.

My question is, what allows the callback function to refer to outside variables in a forward-looking manner? Is this really unique to callback functions only? Thanks.

Upvotes: 0

Views: 42

Answers (1)

Ben Aston
Ben Aston

Reputation: 55729

Control never reaches

var counter = 7;

Therefore your maths uses an undefined value (counter is declared and available for use because it is hoisted). The += operator coerces undefined to NaN and NaN is toxic.

Hence the result.

Upvotes: 1

Related Questions