简体   繁体   English

如何从外部访问匿名函数内部的函数

[英]How do you access a function inside an anonymous function from outside

I am writing some useful functions for my webpage for my webpage. 我正在为网页编写一些有用的功能。 The functions will be inside an anonymous function and will be called from outside the function. 这些函数将在匿名函数内部,并且将从函数外部调用。 When I try to call the functions I get an error. 当我尝试调用函数时,出现错误。 This is how I am constructing it: 这就是我构造的方式:

(function(){
    var fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    fx = window.fx;
})();
window.onload = fx.pop('hi');

Does anyone know how I might do this? 有人知道我该怎么做吗? I know this is possible because jQuery and other javascript libraries are written like that. 我知道这是可能的,因为jQuery和其他javascript库是这样写的。

When you do fx = window.fx; 当你做fx = window.fx; you are overwriting the fx which is in local scope of anonymous function. 您将覆盖匿名函数本地范围内的fx If you want access to it outside in the global scope you would need to do window.fx = fx; 如果要在全局范围之外访问它,则需要执行window.fx = fx; . And Seems like you want to invoke the function pop on load and not when registering on load, Which is what you are trying to do here window.onload = fx.pop('hi'); 而且好像您要在加载时调用pop函数,而不是在加载时调用函数,这就是您要在此处执行的操作window.onload = fx.pop('hi'); This will invoke pop immediately and set the result of method as callback for load event (which is undefined as your method doesn't return anything; unless the method return another function that needs to be invoked after load this becomes useless). 这将立即调用pop并将方法的结果设置为load事件的回调(未定义,因为您的方法不返回任何内容;除非该方法返回另一个需要在加载后调用的函数,否则此函数将变得无用)。 Instead you may want to try this way. 相反,您可能想尝试这种方式。

window.onload = fx.pop.bind(this, 'hi'); //Now this will get invoked only after load event is completed, it bind the current context to the function pop with the argument  `hi`

or 要么

window.onload = function(){
    fx.pop('hi'); //Now this gets invoked only after load event is completed
};

So you can try: 因此,您可以尝试:

(function(){
    var fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    window.fx = fx;
})();
window.onload = function(){
    fx.pop('hi')
};

are you sure jquery and other javascript libraries are written like that? 确定 jquery和其他javascript库是这样写的吗? I don't know of a simple way to gain access to the scope of a function, from outside that function. 我不知道一种从函数外部访问函数范围的简单方法。 this seems like an unusual objective so please explain what problem you are attempting to solve with this technique, perhaps there is a more appropriate strategy. 这似乎是一个不寻常的目标,所以请解释一下您尝试使用此技术解决的问题,也许有更合适的策略。

For instance you could try: 例如,您可以尝试:

var fx;
(function(){
    fx ={
        pop : function(msg){
            alert(msg);
        }
    };
    fx = window.fx; // this will probably overwrite your previous object with undefined
})();
window.onload = fx.pop('hi');

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

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