How come the oldFunc is getting referred from the caller function even though it is a local variable in middleware

43 views Asked by At
var AwesomeClass = function() {
    this.awesomeProp = 'awesome!'
    this.awesomeFunc = function(text) {
        console.log(text + ' is awesome!')
    }
}
var awesomeObject = new AwesomeClass()
function middleware(func) {
   var oldFunc = func.awesomeFunc
    func.awesomeFunc = function(text) {
        text = text + ' really'
        oldFunc(text)

    }
}
function anotherMiddleware(func) {
    func.anotherProp = 'super duper'
}
function caller(input) {
    input.awesomeFunc(input.anotherProp)

}
middleware(awesomeObject)
anotherMiddleware(awesomeObject)
caller(awesomeObject)

In the above code you will see that the caller function is the one that actually makes the call to awesomeFunc but when we called middleware function we changed the function inside the awesomeobject and made oldFunc variable a part of the awesomeFunc. But what i do not understand is how come when the awesomeFunc is called from inside caller function the awesomeFunc executes properly? As awesomeFunc has oldFunc mentioned inside it now which is local variable of the function middleware so the caller function should not be able to recognize it.

1

There are 1 answers

5
barry-johnson On BEST ANSWER

I also updated my answer to your original question with this content, but am putting this here as well.

The reason is that it is available via closure, which to simplify, makes the variables of the enclosing function scope available to the enclosed scope. Incredibly powerful feature, also easy to have some unintended behavior crop up - inner function closures mistakenly accessing an outer looping variable (when they really just wanted to access the value of the loop counter at a specific point in time) are a very common source of headache for some. You can find some very good descriptions of closures on Stack Overflow. This question covers closures pretty well. I also recommend Douglas Crockford's Javscript: The Good Parts for coverage of many of Javascript's feature nuances.