Saturday, September 18, 2010

VbScript Me Keyword

VbScript Me Keyword

The Me Keyword stands for the current (in progress) instance of the class in which code is executing.

An object is an instance of a class. There can be many individual objects that all share the same class methods and properties. Each object however is unique because it has its own set of member variables. This set of member variables is accessed via the object reference. Outside of a class, each object is identified by a variable that contains the object reference. Inside the class, this variable is not accessible, but internally VBScript tracks which object is currently executing the class method or property and makes this information available via the Me keyword. [Windows Script Host by Tim Hill]

Example 1 of Me Keyword


While running the code when the focus comes on line 30, Class_Initialize() sub is executed and my_ctr gets a value of 1. Line 31 is executed next, which runs Increment() sub and increases the value of my_ctr to 2. Line 32 is executed next, which again runs Increment() sub and increases the value of my_ctr to 3. Line 33 is executed lastly which calls Function ShowCount(), ShowCount() in turn calls Function ShowObjectValue(oObj) [passing it current object or current instance, which in our case is oCtr] and Function ShowObjectValue(oObj) shows the current value of oCtr by calling Property Get.

Know more about Class_Initialize and Class_Terminate.
An Example of VBScript Property Let & Property Get.

Example 2 of Me Keyword


While running the code when the focus comes to line 22, Property Get count gets executed which adds 1 to the value and then shows (because line 22 is using Msgbox) the count. On line 24, Property Let count(c) gets executed, which assigns 9 to iCount. Next line 25 calls Property Get count, which adds 1 to the value and then shows the count as 10. Lastly Line 27 shows a value of 'a' as 23! Why? Because before coming to line 27, value of 'a' is 10. When on line 27, Property Get countTwice gets executed, which is calling Property Get count twice, once earlier value of 10 is incremented by 1 and becomes 11 and secondly that 11 becomes 12 and in countTwice these 11 and 12 are being added to 23.

Notice that in countTwice Me is accessing current value of the instance which is 10.