简体   繁体   English

将对“ this”匿名外部函数的引用传递给内部函数

[英]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. 从那里开始,如参数所示,第一个匿名函数会将其状态(带有this )传递给刚刚传入的函数。我遇到的问题是,匿名函数的this引用了全局window ,而不是全局window匿名功能。

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). Javascript使用词法作用域,即,仅物理上位于外部函数内部的函数才能访问其作用域( var )。 There's no way to make function's var s accessible for any function defined outside. 无法使外部定义的任何函数都可以访问该函数的var

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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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