Classic ASP development: eight reasons for choosing JScript instead of VBScript

Source: Internet
Author: User
Tags finally block ldap classic asp
Document directory
  • Reason 4: JScript is object-oriented
  • Reason 5: The Regular Expression Processing capability of JScript is stronger.
  • Reason 7: JScript date processing can avoid local time problems
  • Reason 8: JScript has a better Exception Handling Mechanism
  • Conclusion

I admit that I am an expert in JS server technology. I tried to "enclose the server from the client" for JS language applications. Besides, this is nothing new (ssjs ), there should be people who share the same opinion with me. Although there won't be much enthusiasm for this, or there is no reason to "speak words" for it, there are also a lot of secrets-I think, through the introduction in this article, they will also silently agree with the following statement.

ASP is a technology released by Microsoft more than a decade ago. How many production environments of ASP + COM/DLL are there? I don't know ~. I don't know if it's "unintentional". I think I can find Js in ASP. For me and I want to use JS, it is really "walking through the shoes without looking", haha, although the "Liu chengyin" here may not reach the level described. Since classic ASP (jscript) is an old technology, I don't think there is any capital to "beat everyone", so even if you advocate it, it will be harmless.

This is an article translated by foreigners, and I have only a few reposted articles on my blog. I 've been on the hard disk for a long time. When I want to clean up the old file, I find that the text is still there. -- I 'd like to release it here, so it won't be completely deleted.


Edit: an ASP Server framework written by a Chinese user. Open Source: https://code.google.com/p/js-asp /.

When the first release of active sever page, there are two built-in languages for you to write ASP scripts or HTAs: VBScript and JScript. When ASP 1.0 was released, there were not many methods except VBScript and JScript. But with the upgrade of the Windows Host host (ASP host) and HTML Application (HTAs), this situation has changed. You can install third-party tools, such as Perl, but the operating system itself does not provide the built-in Script Function.

Some developers have already chosen other languages (such as PHP or ROR), and Microsoft has created a new direction by creating ASP. NET. These are good choices, but they are not built into the operating system, and usually, it is very important to have a common underlying management platform (for example, you cannot install it on some machines.. NET Framework ). Although. NET is powerful, it also has a high entry threshold (it must be a version later than Windows XP SP2 and installed with. NET 2.0 ). In contrast, an ASP script written using VBScript or JScript can run in
Windows 2000 and later versions. One common advantage of the two is that they are built into the windows ASP. dll kernel.

Since most ASP developers will need to write ASP page scripts, it is necessary to select the best language to help you complete your work smoothly: JScript.

Reason 1: JScript is more widely used

Based on my experience, many people are vague about what JScript is. In short, JScript is Microsoft's implementation of the ECMA-262 specification, which describes a scripting language called ecmascript. JavaScript and JScript are two of the most widely used ecmascript specifications. In addition to some attribute extensions that are not convenient for COM programming, JScript is now similar to JavaScript (jscript. NET is another different language, beyond the scope of this article ).

As a royalty-free technology, JavaScript/JScript is widely used in different applications on different platforms, and the most important application is in browsers. Other vendors have also used them as automated languages (such as Adobe creativesuite/air. In other words, JScript knowledge can be used in many different places. In contrast, VBScript is dedicated to Microsoft and is only used by Microsoft applications on Windows platforms that use the VBScript interpreter.

Reason 2: JScript is still evolving

As I mentioned above, JScript is based on ECMA-262 standards. Although the current version of JScript is equivalent to ECMA-262 3.0, the forthcoming ECMA-262 3.1 will be backward compatible with 3.0. If ECMA-262 3.1 is widely accepted, Microsoft will also upgrade JScript to maintain browser compatibility.

In contrast, Microsoft keeps VBScript unchanged. This means that Microsoft will only fix some major errors and security vulnerabilities in the VBScript interpreter; it will not add new features or expand the language. Since VBScript is in the maintenance stage, it makes more sense for developers to learn a more futuristic language.

Reason 3: JScript is easier to learn

One of the most widely used vbscripts is that VBScript is easier to master. For various reasons, people think that JScript is hard to learn. This may be because the C programming style of JScript is somewhat different from that of VBScript. However, once you get in, JScript is easy to master.

Many basic concepts are the same (such as declarations, variables, and functions); they just look a little different. Once you understand the basic structure of this language, it is very easy to use JScript instead of VBScript for Script Programming. Similar to the programming authors of most Windows scripts, I started using VBScript, but I found that although some programming concepts are different, JScript and VBScript are equally easy to learn.

Reason 4: JScript is object-oriented

JScript is built as an object-oriented language. Built-in database types (such as strings and numbers) are all objects with methods. For example, the number type has a tostring () method to return a number as a text, while the text type has the touppercase and tolowercase methods to return text in uppercase or lowercase. Using it, you can easily create your own objects in the least encoding mode. See the following example in examples:

VaR Options = {path: "", recurse: false };

This simple line of code creates an object without a name. It contains two attributes and initializes the attributes.

You can also create a user-defined object in VBScript, but it is much more complicated. This language requires you to create a class and initialize the class, as shown in the following code:

Class optionsclass <br/> Public path <br/> Public recurse <br/> private sub class_initialize () <br/> Path = "" recurse = false <br/> end sub <br/> end class <br/> dim options <br/> set Options = new optionsclass 'creates an instance of the class

The object-oriented feature of JScript makes this a simple task. VBScript requires more code to do the same thing.

JScript also allows you to create a named object (which is mandatory in VBScript). If you need multiple such objects, you can define a constructor to define this object. For example:

Function optionsobject (path, recurse) {<br/> This. path = path; <br/> This. recurse = recurse; <br/>}< br/> var Options = new optionsobject ("C: // winnt", true); // create an Instance Object

JScript uses prototype-based inheritance instead of class-based inheritance. With the prototype attribute of an object, you can expand the behavior of an object and add a method to its prototype attribute. For example:

Array. prototype. exists = function (item) {<br/> for (VAR n = 0; n <this. length; n ++) <br/> If (item = This [N]) <br/> return true; <br/> return false; <br/>}

The above Code adds the exists method to this array object. The following is an example of how to use this new method:

VaR myarray = ["A", "B", "C", "D"]; // defines an array containing four elements <br/> var result = myarray. exists ("A"); // returns true <br/> var result = myarray. exists ("e"); // return false

From this example, we can see how flexible the JScript Language is, no matter your own or built-in objects, how easy it is to extend and customize them.

Reason 5: The Regular Expression Processing capability of JScript is stronger.

Regular Expressions are a function of JScript itself; they are embedded in the language syntax. VBScript does not support regular expressions before version 5. Therefore, its syntax is relatively cumbersome and poor. For example, if you want to use a regular expression to check whether the input text is in the email format. In VBScript, you have to use the new keyword and set Declaration to create a Regexp object and configure its attributes for search. The following is an example:

Address = "foo@bar.com" <br/> set Re = new Regexp <br/> with Re <br/>. pattern = "/W + @/W + /. /W + "<br/>. ignorecase = true <br/> end with <br/> result = Re. test (address)

The same JScript code is more concise.

VaR address = "foo@bar.com"; <br/> var Re = // W + @/W + /. /W +/GI; <br/> var result = Re. test (Address );

The second line of code above creates a Regexp object. If you know the mode before the code is executed, the/expression/syntax is a convenient way to describe the mode of a regular expression. As an option, you can use the new operation to create a Regexp object, as shown below:

VaR address = "foo@bar.com"; <br/> var Re = new Regexp ("// W + @ // W + //. // W + "," I "); <br/> var result = Re. test (Address );

This syntax is useful if you want to describe a regular expression pattern at runtime. In addition, the Regexp object of JScript has a compilation method, which can improve the performance when you use them repeatedly, such as using it in a loop.

Reason 6: JScript arrays are much more powerful.

Arrays have always been a pain point in VBScript. They are very inflexible. They can be re-specified only when a fixed number of elements is not specified for the array during definition (for example, if you define an array with five elements, you cannot add the sixth element to the array.) For example, see the following VBScript code in idea:

Dim myarray (4) 'declares that an array can contain up to five elements <br/> myarray (5) = "test"', causing an error: this array can only contain five elements, elements <br/> redim myarray (6) '. Similarly, an error occurs: the array has been defined as a fixed size.

In VBScript, you can create a dynamic array that can modify the size, but this is a two-step process; you have to declare an array first, and then you have to specify the size of it again, specify the correct number of elements since:

Dim myarray () <br/> redim myarray (5) 'redefine the array size <br/> myarray (5) = "test" 'assigns a value to the sixth element of the array

If you want to use a VBScript array to accommodate the variable quantity Elements read from a loop (for example, an array of file objects obtained from the FileSystemObject file set ), you will need to regularly use the redim declaration with the preserve keyword to redefine the size of this array. (Considering the performance, you may not want to use redim after each loop is completed .)

In JScript, arrays are an object type, which is dynamic in nature and provide many methods to operate on them. For example, the push and pop methods are used to append elements to the array and delete elements from the array. The array size is automatically adjusted during the process. The jscript array also has an sort method to support user-defined sorting. For ActiveX objects that return a VBScript-style array (called safearrays or vbarrays by jscript), this array object has a toarray method to convert the safearray array into a JScript array.

In fact, Microsoft seems to have created a dictionary object during the script runtime to overcome the limitation of the VBScript array data type. Because I have been writing code using JScript all the time, I found that there is only one case where I need a dictonary object: return a safearray object from a JScript array (Strangely, this function is not supported internally ). For example:

Function tosafearray (arrayobject) {<br/> var dict = new activexobject ("scripting. dictionary "); <br/> for (VAR n = 0; n <arrayobject. length; n ++) <br/> dict. add (arrayobject [N], ""); <br/> return dict. keys (); // keys returns a safearray <br/>}

When using ActiveX components, sometimes safearrays is required. I use a function similar to the above to convert a JScript array to safearray.

Reason 7: JScript date processing can avoid local time problems

In VBScript, the value of a date is always "local. Depending on the time source, when calculating the date, this may cause Coordinated Universal Time (UTC) and daylight saving time errors. Let's look at a practical example. The pwdlastset Active Directory (AD) User attribute is stored as an interval number since AM January 1, 1601, UTC. The following is an example of how to convert the pwdlastset value to a VBScript date.

Dim userdn, adsuser, lastset, nanosecs, vbtime <br/> userdn = "cn = John Smith, ou = Sales, Dc = wascorp, dc = net "<br/> set adsuser = GetObject (" LDAP: // "& userdn) <br/> set lastset = adsuser. pwdlast <br/> set nanosecs = (lastset. highpart * (2 ^ 32) + lastset. lowpart <br/> vbtime = cdate (#1/1/1601 # + (nanosecs/600000000/1440) 'returns UTC time

This script snippet connects to John Smith's user account object in the Active Directory and returns the pwdlastset attribute of the account. (Set declaration is required because the value of pwdlastset is returned as an object .) Next, the Code converts the value of pwdlastset to a single 32-bit value by reading its highpat and lowpart attributes. (This conversion is just an approximate value, but we ignore this tiny difference .) Finally, the Code increases the number of days to 12: 00 AM January 1, 1601 to get the final result.

The value obtained from this result is in UTC. VBScript does not provide a method to convert the date to the local time. I have seen some sample code to adjust the local time by reading the local time offset from the registry. However, this is a very troublesome and fragile solution. First, it assumes that the account running the script has the permission to read the registry value. Second, it assumes that the registry value has never been changed, third, it cannot adapt to the adjustment during the timeout period, and does not know whether the returned result is after a DST change. For example, if we want to calculate the date and time when a user's password will expire in the future, the current local time offset may be modified due to DST in the future, and thus become inaccurate.

In JScript, the date is processed by the date object. The date object of JScript can be used to represent any date and time, obtain the current system date, and calculate the date difference. It has several predefined attributes and methods. Date objects are stored on a certain day of a week; months, days, and years; and time in hours, minutes, seconds, and milliseconds. This information is based on the number of milliseconds since Coordinated Universal Time (UTC) January 1, 1970 00:00:00. 000. The following is equivalent code in JScript:

VaR userdn, adsuser, lastset, nanosecs, jstime; <br/> userdn = "cn = John Smith, ou = Sales, Dc = wascorp, Dc = net "; <br/> adsuser = GetObject ("LDAP: //" + userdn); <br/> lastset = adsuser. pwdlastset; nanosecs = (lastset. highpart * (math. pow (2, 32) + lastset. lowpart); <br/> // natively stored as UTC <br/> jstime = new date (date. UTC (1601, 0, 1, 0, 0, 0, nanosecs/10000 ));

This code is the same as the VBScript code above. It copies the value of pwdlastset to a 32-bit value. However, note that the last line of the Code uses the UTC method of the date object to construct a UTC date. The most beautiful thing is that when you retrieve this value, JScript knows how to convert it to the local time. I used an account in my own domain to complete this experiment. The return time of VBScript is 16 May 2007, while that of JScript is 16 May 2007. Note that the answer to JScript is correct. The local time is instead of, because my local time zone is 6 hours earlier than UTC.

Reason 8: JScript has a better Exception Handling Mechanism

VBScript has a very simple Exception Handling Mechanism, which consists of two program declarations: On Error resume next disables the default error handling mechanism, on Error goto 0, the default error handling mechanism is enabled. If the default error handling handle is disabled and an error occurs, VBScript updates the properties of the ERR Object. This means that if you have a series of declarations that may cause errors, you will have to check the ERR Object after each declaration, only when the number attribute of this ERR Object is 0, to continue the following code. The following code is used:

On Error resume next <br/> dim FSO, TS <br/> set FSO = Createobject ("scripting. fileSystemObject ") <br/> set Ts = FSO. createtextfile ("C:/logfile.csv") <br/> If err = 0 then <br/> TS. writeline ("lastname, firstname, email") <br/> If err = 0 then <br/> logdata <br/> end if <br/> TS. close () <br/> end if

The above code tries to create a text file; if it succeeds, it then tries to write a line of text into the file. If the writeline method is successfully executed, the above script will only execute logdata? Function. If you need to check multiple errors, it is very difficult to track the script logic. In contrast, JScript uses a block-based exception handling mechanism, allowing you to easily handle errors without checking errors in every declaration. The JScript code equivalent to the above Code is as follows:

VaR FSO, TS; <br/> FSO = new activexobject ("scripting. fileSystemObject "); <br/> try {<br/> TS = FSO. createtextfile ("C:/logfile.csv"); <br/> TS. writeline ("lastname, firstname, email"); <br/> logdata (); <br/> TS. close (); <br/>}< br/> catch (ERR) {<br/> // put error-handling code here <br/>}

This try {...} block indicates the code that may generate errors. If an error occurs, the execution of the script jumps to the Catch Block. The err variable contains an object that contains detailed error information. JScript also supports a Finally block, which is usually located behind the try and catch blocks. It contains the code to be executed after the try block (and Catch Block, if an error occurs. For example, a script can be used to release a resource, whether or not an error occurs.

Conclusion

JScript is built in the best Windows Active language in the operating system. In this article, I give eight reasons why it is more powerful than VBScript. I think ASP developers should study this powerful language well.

 

Also: See the discussion in this section: JScript is the most suitable server side language for Ext.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.