views:

69

answers:

2

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. 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?

+8  A: 

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.

galambalazs
Yes, you right, sound strange, but I need this behavior.
Alex Ivasyuv
+3  A: 

You can't pass the scope as an object, but you can create an object with whatever you want from the scope:

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