user3621156
user3621156

Reputation: 65

Javascript - keeping variable in scope after function has been declared

I have some javascript code that takes a function and invokes it again:

var obj = {
  // returns the function with prevent default prepended.
  run: function(functor, context){

    return function(e){
      e.preventDefault();
      context.call(functor, e);
    };
  }
}

var myContext = this;
var returnedFunction = obj.run(function(e){alert(e.target)}, myContext);
var returnedFunction(...);

Here is the problem:

On the line where it says context.call(functor, e);

context is always null because the function has gone out of scope.

What do I have to do inside that function so that I can use context?

Upvotes: 0

Views: 233

Answers (1)

apsillers
apsillers

Reputation: 115940

context has not gone out of scope -- it's probably just null to begin with (and even if it weren't, it likely wouldn't have a call method).

Instead, you probably meant to use functor.call(context, e).

Functions have a call method, which accepts a this/context argument and variable-length following arguments. Objects in JavaScript generally don't have a call method that accepts a function and variable-length following arguments (unless you've added such a method and expect context to have it).

Upvotes: 3

Related Questions