views:

604

answers:

2

How to pass current scope variables and functions to the anonymous function in plain Javascript or in jQuery (if it's specific for frameworks).

For example:

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

Should log in firebug everything from 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!

A: 

Before line 1:

var that = this;

Then change line 4:

onSomeEvent.apply(that);
David Dorward
And how to call functions and variables? Using this.variable?
Dmitry Polushkin
Isn't work: http://gist.github.com/152649
Dmitry Polushkin
Simplefied: (function(){var _this = this;var a = 2;console.log(_this.a);})(); - how to get a variable from another variable, hash or I don't know what else...
Dmitry Polushkin
A: 

Read about Scopes in JavaScript for example in "Java Script: The good parts".

In the Java Script there is only scope inside Functions. If you specify your variable inside function with var you can't access them from outside of this function. This is way to make private variables in JavaScript.

You can use this variable, that point to current object you are in (this is not a scope itself). But! if you initiate function without new command, than this will point to outer scope (in most cases it's window object = global scope).

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(); //b.a == 10
var b = bar(); //b.a == undefined, but a in global scope

Btw, check out syntax of apply method Mozilla docs/apply So you can see, that fist argument is object, that will be this when your method will be 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 it's better to make

var that = this;

before calling apply method, but maybe it's not needed. not sure

So, this definitely will work:

function foo(){
  console.log(this.a);
}
jQuery.extend({
 somefunc: function(func){
   this.a = 10;
   func.apply(this);
 }
});

$.somefunc(foo); //will print 10.
Aleksandr Motsjonov