Extract variable
Extract one or more occurrences of an expression into a const
variable.
Refactoring (Extract)
P42 for VS Code
To extract a variable, you need to select the full expression that you would like to extract, and then invoke the refactor or extract context menu.
What do I need to consider?
Extracting targets of method calls can change the 'this' reference
Consider the following example:
const anObject = {
doSomething() {
console.log({
isObject: this === anObject,
isGlobal: this === globalThis
})
}
}
anObject.doSomething(); // prints { isObject: true, isGlobal: false }
Extracting anObject.doSomething
into a new variable extracted
changes the this
reference of the method call and its behavior:
const extracted = anObject.doSomething;
extracted(); // prints { isObject: false, isGlobal: true }
Assignment targets are not extracted
The left side of assignment expressions is not extracted, because it would change the program behavior.
Consider following example:
anObject.aProperty = 123; // assignment to anObject.aProperty
Extracting anObject.aProperty
into a variable would mean that the assignment would change the variable, but not the object property:
const aVariable = anObject.aProperty;
aVariable = 123; // does not change anObject.aProperty
P42 does not extract such assignment targets.
Configuration
- Code Assist ID (for the configuration file):
extract-variable
- You can configure custom keyboard shortcuts with this code action kind:
refactor.extract.p42.extract-variable
Related Code Assists
- Inline variable
- Extract selected text into variable
- Extract React function component
- Replace with existing variable
- Select expression occurrences