简体   繁体   中英

Passing reference to “this” anonymous outer function to passed inner function

For the sake of maintaining a namespace, I have code that looks something like this:

MyNamespace = function() {
    var foo;
    //other private vars

    //some private functions

    //return certain functions which will be publicly called through MyNamespace
    return {
        "pubFunc1": function() {/*do stuff*/}
    }
}

I'd like one of my public functions to be able to take a function as a parameter. The function being passed in would look something like this:

function(state) {
    //do something with the passed in state
}

This function would be passed into the first anonymous function. From there, as implied by the parameter, the first anonymous function would pass its state (with this ) to the function that was just passed in. The problem I run into is that the this of an anonymous function refers to the global window , not to the anonymous function.

What I really need is the ability to pass in a function and give it full access to the private variables and functions within my namespace function. Does anyone know a good way to do this?

Javascript uses lexical scoping, that is, only functions physically located inside an outer function have access to its scope ( var s). There's no way to make function's var s accessible for any function defined outside.

So your only option to make "private" vars into "protected" properties and pass the properties bag to the callback:

 MyNamespace = function() {
    return {
        _foo: "something",
        _bar: "else",
        pubFunc1: function(callback) {
             callback(this._foo, this._bar) //or
             callback(this)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM