Create a new context for an function

Lets say I have an ajax call like this:

$.ajax({ ... success : someFn })

On the code review, they asked about what environment does someFn have access to? They were more worried about, what all variables, scopes does someFn have access to and how I'm going to manage the changes that are done in someFn.

For example if :

someFn : function() { //1. changes some object value //2. Works based on some scope variables }

Now the question is:

  1. How I can send the scope variables to someFn and reason about them?
  2. If the scope variables is an reference to another object, how should I handle those changes within someFn.

Thanks in advance

-------------Problems Reply------------

The variables in scope for someFn are determined by where someFn is defined, not where you've used it. Using it in your ajax call does nothing to grant it access to anything it doesn't already have access to.

The variables in scope for a function are the ones in scope where it's created, which are: The locals for the context where it's created, the context containing that context, the context containing that context, and so on through the global context.

So:

function foo() {
var a;

function bar() {
var b;
}

return bar;
}

The code in foo has access to all global variables, and also its local variable a. bar has access to all global variables, the a variable created by the call to foo that created bar, and (of course) its local variable b.

More (on my blog): Closures are not complicated

If you have context information that you need to pass to someFn from your ajax context, you'll need to define a new function that passes that information to someFn as arguments. (Either explicitly, or using Function#bind, which creates a new function which, when called, calls the original with a specific this value and any other arguments you give bind.)

  1. pass the scope variables to someFn by

    success : function(){
    someFn(scope_var1, scope_var2);
    }

    • you could as well use the bind method to preserve the this context
  2. incase you make changes to that object take into account that it would affect anyone using it. You could either clone your object $.extend(true,clonedObj,someObj)
Category:javascript Views:1 Time:2018-10-07

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.081 (s). 11 q(s)