简体   繁体   English

javascript匿名函数范围

[英]javascript anonymous function scope

I have the following anonymous function: 我有以下匿名功能:

(function() {
 var a = 1;
 var b = 2;

 function f1() {
 }

 function f2() {
 }

 // this => window object!
 // externalFunction(this);
})();

function externalFunction(pointer) {
 // pointer.f1(); => fail!
}

I need to call external function from this anonymous function and pass it's pointer to call functions f1 & f2. 我需要从这个匿名函数调用外部函数,并将它的指针传递给调用函数f1和f2。 But I can't do this, as this refer to window object instead of internal scope. 但我不能这样做,因为这引用了窗口对象而不是内部范围。

I can set function as: 我可以将功能设置为:

this.f1 = function() {}

but it's bad idea, as they'll be in global space... 但这是个坏主意,因为他们将在全球空间......

How I can pass anonymous space to external function? 如何将匿名空间传递给外部函数?

I still wonder why you would make functions to be private, that are needed outside... But there you go: 我仍然想知道为什么你要把功能变成私人的,外面需要的......但是你去了:

(function() {
  var a = 1;
  var b = 2;

  var obj = {
    f1: function() {
    },
    f2: function() {
    }
  }

  externalFunction(obj);
})();

function externalFunction(pointer) {
  pointer.f1(); // win
}

Or you can pass f1 and f2 individually, then you don't need to put them into an object. 或者您可以单独传递f1和f2,然后您不需要将它们放入对象中。

您不能将范围作为对象传递,但您可以使用范围内的任何内容创建对象:

externalFunction({ f1: f1, f2: f2 });

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

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