Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 482
Alex Ivasyuv Avatar asked Aug 17 '26 04:08

Alex Ivasyuv


2 Answers

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.

like image 97
25 revs, 4 users 83% Avatar answered Aug 18 '26 19:08

25 revs, 4 users 83%


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 });
like image 30
Guffa Avatar answered Aug 18 '26 18:08

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!