vbscriptechowshcreateobject

Why do I have to write WScript.Echo with WScript while it's not mandatory for CreateObject?


In VBScript, there're so many examples where users wrote WScript.CreateObject("...") while at the same time the script56.chm and other relevant docs advise to just write CreateObject("..."). And it seems to work the same way.

I'm wondering why is it different for WScript.Echo (you can't just write Echo...)

I read the following question and comments about the reason behind WScript.CreateObject but didn't seem to find anything relevant: What is the difference between CreateObject and Wscript.CreateObject?

Or did I miss something?


Solution

  • You see an incongruity because you think you are using the same thing in both cases, but you are not.

    You have two different elements that collaborate to run your scripts: a script host and a script engine. The script host is the executable that initializes the scripting engine who deals with the language used. In an usual client OS install you have at least three script hosts (wscript.exe, cscript.exe, mshta.exe) that can use two different script engines (VBScript and JScript).

    WScript.CreateObject is a method of the WScript object exposed by the script host (cscript.exe or wscript.exe) to allow the scripting engine (as said VBScript and JScript are native to the OS, but you can install other engines) instantiate a COM object.

    CreateObject (no WScript here) is a function of the VBScript script engine, not related to the WScript object or the script host.

    Both share the same name, but they are not the same thing. Calling CreateObject function in VBScript is "equivalent" to use new ActiveXObject( ... ) in JScript. In both cases you use something the scripting engine exposes, not something the script host exposes.

    By example, you can use any of the two (CreateObject or new ActiveXObject( ... )) inside an .hta file without problems as they are part of the scripting engine, but you can not use WScript.CreateObject in an .hta file because the script host (mshta.exe) does not expose an WScript object to the scripting engine running the code.