Passing scope to callback function / binding

前端 未结 3 1037
梦毁少年i
梦毁少年i 2020-12-23 15:18

I am attempting to pass function scope to a callback method. The problem I am having is that I am getting object scope, which does not provide me with access to the paramet

3条回答
  •  被撕碎了的回忆
    2020-12-23 15:50

    I was a bit quick on my first answer and left some gapping wholes as stated by Maxym in the comments below, thanks for informing me :) That's what I get for trying to post quickly before going back to work :P

    What I was trying to get at in my first answer is if you want to use binding to access variables in function lookup from function myHandler (which is outside the scope of lookup) you would have to not use var but this instead.

    Using var would make it only accessible to lookup's private scope and any functions nested in it, which is how the other answers have demonstrated (and are probably the best route)

    Below is an updated example of how to pass lookup's scope to myHandler leaving myHandler completely out of lookup's scope. Hopefully this will help shed a bit of light on:

    "The problem I am having is that I am getting object scope, which does not provide me with access to the parameters and local variables in the original function."

    As stated in the comments about my previous answer this can get tricky and you can end up adding things to the global scope if not careful like I did in my first example. :( So I've added a bit of a hack'ish check to see what scope this is making sure it's not window for demonstration purposes...

    Live Example

    function myHandler(data, ctx) {
        console.log('myHandler():  bar: ' + this.bar); // <- must use `this`
        console.log('myHandler():  privateBar: ' + this.privateBar); // <- undefined because it's privately scoped
        console.log(JSON.stringify(data));
    }
    MySvcWrap = {
        doWork: function(p1, callback, scope) {
            var result = {
                colors: ['red', 'green'],
                name: 'Jones',
                what: p1
            };
            if (callback) {
                callback.call(scope || this, result, scope);
            }
        }
    }
    
    function lookup() {
        if(this == window) return lookup.call(lookup); // <- my hack'ish check
    
        var privateBar = 'private food'; // private local var
        this.bar = 'food'; // public local var
        MySvcWrap.doWork('thang', myHandler, this); // scope object is this
    }
    
    lookup();
    
    console.log('global space - bar: ' + this.bar);
    

提交回复
热议问题