1

I have a code like:

$(function () {

    var addUserUrl = 'some string from the app';

    $('.select2').on('change', function() {
        console.log( addUserUrl );
        // Next line is the problem because of redefinition of var
        var addUserUrl = addUserUrl.replace(/idHolder/, $(this).val();
    });

});

and as I see addUserUrl in onChange callback is undefined. I am little confused. The scope of lambda function is the same as scope of addUserUrl in my opinion. Can somebody explain me please what happens there?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Čamo
  • 3,863
  • 13
  • 62
  • 114
  • This is not valid JavaScript; the code won't parse, and so cannot run: `var addUserUrl = {link addUser! id => 'idHolder'};`. If it weren't for that, the event callback would access `addUserUrl` just fine: http://jsfiddle.net/2wqeyL7t/ – T.J. Crowder Sep 11 '18 at 18:24
  • I am sorry thi is only example. I'll fix it. – Čamo Sep 11 '18 at 18:25
  • The code in your edit will work just fine (see my edited comment above, we crossed paths :-) ). – T.J. Crowder Sep 11 '18 at 18:26
  • I would suggest making a snippet of this example to see if you can reproduce the problem — as it is, it works just fine for me. – Mark Sep 11 '18 at 18:28
  • I have it. This code works fine. But in my original code lambda contains a line with ```var addUserUrl = addUserUrl.replace(/idHolder/, id);``` which redefine the variable. – Čamo Sep 11 '18 at 18:33
  • 6
    Using `var addUserUrl` in the inner function _hides_ the variable of the outer scope. So just use another variable name in the inner function: `var updatedAddUserUrl = addUserUrl.replace(/idHolder/, id)` – t.niese Sep 11 '18 at 18:40

0 Answers0