admin管理员组

文章数量:1291174

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?

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?

Share Improve this question edited Jul 5, 2010 at 11:41 gblazex 50.1k12 gold badges99 silver badges92 bronze badges asked Jul 5, 2010 at 11:31 Alex IvasyuvAlex Ivasyuv 8,84417 gold badges75 silver badges91 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 9

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.

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

本文标签: oopjavascript anonymous function scopeStack Overflow