@@ -93,6 +93,63 @@ export class Guard {
9393 return this . containsToken ( 'Keyword' , 'this' , node ) ;
9494 }
9595
96+ containsThisDirectly ( node : TSESTree . Node ) : boolean {
97+ // Check if 'this' is used directly in the current function, excluding nested functions
98+ const visit = ( currentNode : TSESTree . Node | null | undefined , insideNestedFunction : boolean ) : boolean => {
99+ if ( ! currentNode || typeof currentNode !== 'object' || ! currentNode . type ) {
100+ return false ;
101+ }
102+
103+ // If we find a 'this' expression and we're not inside a nested function, return true
104+ if ( currentNode . type === AST_NODE_TYPES . ThisExpression && ! insideNestedFunction ) {
105+ return true ;
106+ }
107+
108+ // Check if current node is a nested function
109+ const isNestedFunction =
110+ currentNode . type === AST_NODE_TYPES . FunctionDeclaration ||
111+ currentNode . type === AST_NODE_TYPES . FunctionExpression ||
112+ currentNode . type === AST_NODE_TYPES . ArrowFunctionExpression ;
113+
114+ // If we encounter a nested function, mark that we're inside one for its children
115+ const newInsideNestedFunction = insideNestedFunction || ( isNestedFunction && currentNode !== node ) ;
116+
117+ // Skip traversing function body if this is a nested function (not the root)
118+ if ( isNestedFunction && currentNode !== node ) {
119+ return false ;
120+ }
121+
122+ // Recursively check all child nodes
123+ for ( const key in currentNode ) {
124+ if ( key === 'parent' || key === 'range' || key === 'loc' ) {
125+ continue ; // Skip these properties to avoid circular references
126+ }
127+
128+ const child = currentNode [ key as keyof TSESTree . Node ] ;
129+
130+ if ( child && typeof child === 'object' ) {
131+ if ( Array . isArray ( child ) ) {
132+ for ( const item of child ) {
133+ if ( item && typeof item === 'object' && 'type' in item ) {
134+ if ( visit ( item as TSESTree . Node , newInsideNestedFunction ) ) {
135+ return true ;
136+ }
137+ }
138+ }
139+ } else if ( 'type' in child ) {
140+ if ( visit ( child as TSESTree . Node , newInsideNestedFunction ) ) {
141+ return true ;
142+ }
143+ }
144+ }
145+ }
146+
147+ return false ;
148+ } ;
149+
150+ return visit ( node , false ) ;
151+ }
152+
96153 containsArguments ( node : TSESTree . Node ) : boolean {
97154 return this . containsToken ( 'Identifier' , 'arguments' , node ) ;
98155 }
@@ -178,7 +235,7 @@ export class Guard {
178235 ! this . isGeneratorFunction ( fn ) &&
179236 ! this . isAssertionFunction ( fn ) &&
180237 ! this . isOverloadedFunction ( fn ) &&
181- ! this . containsThis ( fn ) &&
238+ ! this . containsThisDirectly ( fn ) &&
182239 ! this . containsSuper ( fn ) &&
183240 ! this . containsArguments ( fn ) &&
184241 ! this . containsNewDotTarget ( fn ) ;
0 commit comments