Pass jQuery / plainJS variables / functions to the current scope for an anonymous function called from the current scope

How to pass the current scope variables and functions to an anonymous function in plain Javascript or in jQuery (if this applies to frameworks).

For instance:

jQuery.extend({ someFunction: function(onSomeEvent) { var variable = 'some text' onSomeEvent.apply(this); // how to pass current scope variables/functions to this function? return null; _someMethod(arg) { console.log(arg); } } }); 

Must go into firebug all of the function above:

 jQuery.someFunction(function(){ console.log(this.variable); // or console.log(variable); console.log(this._someMethod(1); // or jQuery.someFunction._someMethod(2); }); 

Thanks!

+4
source share
2 answers

Read about Scopes in JavaScript, for example, in Java Script: The Good Parts.

In Java Script, there is only a scope inside functions. If you specify a variable inside a function using var , you cannot access it from outside this function. This is a way to make private variables in JavaScript.

You can use the this variable, which points to the current object you are in (this is not the area itself). But! if you initiate a function without a new command, than , this will point to the outer region (in most cases this is a window = global region object).

Example:

 function foo(){ var a = 10; } var f = foo(); //there is nothing in f var f = new foo(); //there is nothing in f function bar(){ this.a = 10; } var b = new bar(); //ba == 10 var b = bar(); //ba == undefined, but a in global scope 

Btw, check the syntax of the apply Mozilla docs / apply method. So you can see that the fist argument is the object that will be this when your method is called.

So, consider this example:

 function bar(){ console.log(this.a); console.log(this.innerMethod(10)); } function foo(){ this.a = 10; this.innerMethod = function(a){ return a+10; } bar.apply(this); } var f = new foo(); // => you will get 10 and 20 in the console. var f = foo(); // => you will still get 10 and 20 in the console. But in this case, your "this" variable //will be just a global object (window) 

Maybe better to do

 var that = this; 

before calling the apply method, but maybe it is not needed. not sure

So this will definitely work:

 function foo(){ console.log(this.a); } jQuery.extend({ somefunc: function(func){ this.a = 10; func.apply(this); } }); $.somefunc(foo); //will print 10. 
+3
source

Before line 1:

 var that = this; 

Then change line 4:

 onSomeEvent.apply(that); 
0
source

All Articles