0

I have a cfc that is a service. It only has functions. Up until now did not have any member variables.

login.cfc

function post(required string email, required string password) { 

  ...

  variables.password = arguments.password; // wish I didn't have to do this
  var User = entityLoad("Users", {email : arguments.email}).filter(
      function(item){
        return item.validatePassword(variables.password);
      });
  variables.password = "";
  ...

I don't like that I have to set arguments.password to variables.password just so that the function inside of .filter can see it. Isn't there a cleaner way to do this?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72

1 Answers1

2

In CF11 and newer, including Lucee 4/5, CFML closures can access variables in the parent scope (and up the stack). CF10 seems to have problems with this... but here's the code you can run in https://trycf.com to see how it works on each version of ColdFusion:

<cfscript>
function doFilter(term) {
    var superheroes=[
           {"name":"Iron Man","member":"Avengers"},
           {"name":"Wonder Woman","member":"Justice League"},
           {"name":"Hulk","member":"Avengers"},
           {"name":"Thor","member":"Avengers"},
           {"name":"Aquaman","member":"Justice League"}
     ];

    var filtered=superheroes.filter(function(item){
       return item.member==term;
    });
    writeDump(filtered);
}

doFilter("Avengers");
</cfscript>

So, in other words, you should have access to the arguments in the post() method if you're using CF11 or newer, or Lucee.

Redtopia
  • 4,947
  • 7
  • 45
  • 68
  • In your sample code `filterTerm` would have the same scope as `variables.filterTerm` wouldn't it? – James A Mohler Nov 21 '18 at 05:29
  • No, because the `variables scope` is global to your component, and the `local scope` is limited to the method where it's defined. Use `var myLocalVar = "something";` to define a local variable inside a function, or you can also just name it `local.myLocalVar = "something";` – Redtopia Nov 21 '18 at 06:45
  • 1
    To clarify and provide a better test, I wrapped the original code example into a function. Note how I'm not using the scope name when referencing the argument `term`. This is because if you write `arguments.term`, you would be referencing the argument scope of the closure function. – Redtopia Nov 21 '18 at 06:51