VBScript Class member variables was override by outer constants
Asked Answered
G

1

2

I found that vbscript class member variables can be replaced by outer constants value.

Example VBScript code:

''' save as test.vbs file
Class Person
  Private name
  Public Sub hi
    name= "inner_name"
    msgbox name  'will be "outer_name"
  End Sub
End Class

set p = new Person
p.hi

Const name = "outer_name"

You can run this code in vbs file or classic asp file.

Save the code into a test.vbs and double click to run it. You will see "outer_name".

enter image description here

Why not "inner_name"?

According to my understanding, the class private member variables should not be affected by outer code.

Can it be fixed?


Here is my workaround finally:

  1. Use Sub or Function with ()
  2. Use Public with Me.XX
Class Person
  Public Function name()
    name= "inner_name"
  End Function
  Public Sub hi
    msgbox name  'will be "outer_name"
    msgbox name()  'will be "inner_name"
    msgbox me.name  'will be "inner_name"
    msgbox me.name()  'will be "inner_name"
  End Sub
End Class

set p = new Person
p.hi

Const name = "outer_name"

Grits answered 11/4, 2023 at 14:13 Comment(1)
You create a global constant (which can't be altered) that will be available at runtime. This constant will trump your class private member (as they have the same name) because the compiler doesn't know the difference. Recommend using a set naming convention for global constants to avoid conflicts. Relevant - Constant inside class.Clydesdale
C
2

You create a global constant (which can't be altered) that will be available at runtime. This constant will trump your class private member (as they have the same name) because the compiler doesn't know the difference.

Recommend using a set naming convention for global constants to avoid conflicts.


Useful Links

Clydesdale answered 11/4, 2023 at 14:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.