0

I was wondering if it is possible to replace the scope object of a function in javascript. I have an event handler that is quite complicated, and I want to pull it out of another function and store it somewhere else. I then would like to be able to retrieve the handler, replace its scope, and pass it along as the handler.

Sample code:

function A(event){

}

function B(){
// many variables initialized here that I want to be available from within A...
// the line where I would like to bind these variables to A
$form.on("submit", A);
}
1
  • question is unclear can u be specific Commented Sep 28, 2013 at 10:06

3 Answers 3

2

JavaScript has lexical scopes, so, it does not provide exactly what you want, i.e. make variables available from where function was used. But you can work around it with the following code:

function A(a,b,c){
    return function(event) {
        /* a, b, c are now available in handler */
        alert(a+b+c);
    };
}

function B(){
    // here you define a, b, c
    var a = 1, b = 2, c = 3;
    $form.on("submit", A(a,b,c));
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think your function A is executed the first time B() is called regardless of whether the submit has been pressed. See: jsfiddle.net/A35tL/1
@meewoK You are right, that is where @voltair wants to bind variables to A and that is where handler for submit is set up. If he wants to alert on submit he should put alert(a+b+c) inside function (event) { alert(a+b+c); }
0

you can always just return the values you want from the function if this is what you need for example, if A() calls for B, you can place return these values:

function B(){return var x = *;}

if A() is getting called from B, you can pass these variables as parameters:

function B(){
$form.on("submit",A(x));
}

or you can just use a global space for your app where everything is visible to all. for any more info please comment so that i can explain more.

Comments

0

you can use a closure to do this:

(function() {
  // declare variables here
  var variable;

  function A(event){
    // use them here
    alert(variable);
  }

  function B(){
  // initialize them here
    variable = 'something';

    $form.on("submit", A);
  }

  B();

})();

or like this:

$form.on("submit", function() { A(var1, var2, var3) });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.