2
votes

I would like to refactor a variable inside a function, but only inside that function. Is this possible in the JetBrains IDE's?

Example:

var global = 0;

function func1 (val) {
    if (val === global) {
        doSomething();
    } else if (val * 2 === global) {
        doSomethingElse();
    } else {
        doSomethingElseEntirely();
    }
}

function func2 (val) {
    if (val === global) {
        doSomething();
    } else if (val * 2 === global) {
        doSomethingElse();
    } else {
        doSomethingElseEntirely();
    }
}

If I try to change the variable global inside func1 via refactor, it will be changed in all of globals scope, so in func2 as well. I would like to prevent this. Is this possible?

2
You are trying to refactor global variable .. so no -- your scenario is not possible. Your options: multi-caret editing or simple find/replace in selection.LazyOne

2 Answers

2
votes

Here is a simpler workaround.

webstorm refactoring

  1. Add a dummy var global within func1.
  2. Use the Refactor > Rename tool (Shift + F6), while selecting any occurrence of global in func1.
  3. Remove the line (place the caret in the line and hit Ctrl + Y) added in step 1.
1
votes

As far as I know "current file" is the smallest scope possible.

Workaround:

To achive what you want with the least effort, I suggest to use the normal search.

  1. Search "global" (Strg + F)
  2. place the cursor before or above the first occurence of "global" in your function (to get right starting point and remove focus from the search field)
  3. click "Add Selection for Next Occurence" (or Alt+J) as often as needed
  4. rename all occurences at once by typing in the new name

some manual work needed here, but I think its the fastest way for big functions.