Java in-depth: write Advanced JScript application code

Source: Internet
Author: User
Java depth: write Advanced JScript application code-general Linux technology-Linux programming and kernel information. The following is a detailed description. 1. Create an advanced object
Use constructors to create objects
A constructor is a function that calls it to demonstrate and initialize special types of objects. You can use the new keyword to call a constructor. The following is a new example of using constructors.

Var myObject = new Object (); // create a common Object without attributes.
Var myBirthday = new Date (1961, 5, 10); // create a Date object.
Var myCar = new Car (); // create a user-defined object and initialize its attributes.
The constructor transmits a parameter as the value of the specific this keyword to the newly created null object. Then, the constructor is responsible for initializing the new object (creating attributes and providing their initial values ). After completion, the constructor returns a parameter of the object it constructs.

Compile Constructor
You can use the new operator to create and initialize an Object with predefined constructors such as Object (), Date (), and Function. Object-Oriented Programming its powerful feature is the ability to define custom constructor to create custom objects used in scripts. A user-defined constructor is created to create objects with defined attributes. The following is an example of a user-defined function (note the use of this keyword ).

Function Circle (xPoint, yPoint, radius ){
This. x = xPoint; // The x coordinate of the center.
This. y = yPoint; // y coordinate of the center.
This. r = radius; // the radius of the circle.
}
When the Circle constructor is called, the value of the center point and the Circle radius are given (all these elements are required to completely define a unique Circle object ). At the end, the Circle object contains three attributes. The following describes how to use a Circle object.

Var aCircle = new Circle (5, 11, 99 );
Use a prototype to create an object
When writing constructors, you can use the attributes of the prototype object (which is an attribute of all constructors) to create inheritance attributes and share methods. Prototype attributes and methods are copied to each object in the class by reference, so they all have the same value. You can change the value of the prototype attribute in an object. The new value overwrites the default value, but is only valid for this instance. Other objects belonging to this class are not affected by this change. The following is an example of using a custom constructor, Circle (note the use of this keyword ).

Circle. prototype. pi = Math. PI;
Function ACirclesArea (){
Return this. pi * this. r * this. r; // the formula for calculating the circular area is? R2.
}
Circle. prototype. area = ACirclesArea; // The function for calculating the circular area is now a method of the Circle Prototype object.
Var a = ACircle. area (); // This is how to call the area function on the Circle object.
With this principle, you can define additional attributes for pre-defined Constructors (all with prototype objects. For example, if you want to delete spaces before and after a String (similar to the Trim function of VBScript), you can create your own method for the String prototype object.

// Add a function named trim
// A method of the prototype object of the String constructor.
String. prototype. trim = function ()
{
// Use a regular expression to separate spaces
// Replace it with a null string.
Return this. replace (/(^ \ s *) | (\ s * $)/g ,"");
}

// A string with spaces
Var s = "leading and trailing spaces ";

// Display "leading and trailing spaces (35 )"
Window. alert (s + "(" + s. length + ")");

// Delete leading and trailing Spaces
S = s. trim ();
// Display "leading and trailing spaces (27 )"
Window. alert (s + "(" + s. length + ")");

2. Recursion
Recursion is an important programming technology. This method is used to allow a function to call itself from within it. An example is to calculate the factorial. The factorial of 0 is particularly defined as 1. The factorial of a larger number is obtained by calculating 1*2 *... and increases by 1 every time until the number of the factorial to be calculated is reached.

The following section defines a function used to calculate factorial.

"If the number is smaller than zero, it is rejected. If it is not an integer, It is rounded down to an adjacent integer. If the number is 0, the factorial is 1. If the number is greater than 0, it is multiplied by the factorial of a smaller adjacent number ."

To calculate any factorial of a number greater than 0, at least one factorial of another number is required. The function that is used to implement this function is a function that is located in it. Before executing the current number, the function must call it to calculate the factorial of adjacent decimal places. This is a recursive example.

Is recursion closely related to iteration? Recursive Algorithms can also be iterated, and vice versa. A definite algorithm can be implemented in several ways. You only need to select the most natural and appropriate method or one of the easiest ways to use.

Obviously, this may cause problems. It is easy to create a recursive function, but this function cannot get a definite result and cannot reach an endpoint. This recursion will cause the computer to execute an "infinite" loop. The following is an example: the first rule (processing of negative numbers) is omitted in the text description of factorial calculation, and a factorial is attempted to calculate any negative number. This will lead to failure, because when we calculate the-24 factorial in sequence, we first have to calculate the-25 factorial; however, we have to calculate the-26 factorial; so we continue. Obviously, this will never reach a termination point.

Therefore, you should be careful when designing recursive functions. If you suspect that there is an infinite recursion possibility, you can let the function record the number of times it calls itself. If the function is called too many times, it exits automatically even if you have determined how many times it should be called.

The following is still a factorial function, which is written in JScript code this time.

// Calculate the factorial function. If
// Invalid value (for example, less than zero ),
//-1 is returned, indicating that an error has occurred. If the value is valid,
// Convert the value to the nearest integer and
// Returns the factorial.
Function factorial (aNumber ){
ANumber = Math. floor (aNumber); // if this number is not an integer, It is rounded down.
If (aNumber <0) {// if the number is smaller than 0, the request is rejected.
Return-1;
}
If (aNumber = 0) {// if it is 0, its factorial is 1.
Return 1;
}
Else return (aNumber * factorial (aNumber-1); // otherwise, recursion is completed.
}


3. variable range
JScript has two variables: global and local. If a variable is declared outside the definition of any function, the variable is a global variable, and the value of the variable can be accessed and modified throughout the continuous range. If a variable is declared in the function definition, the variable is a local variable. This variable is created and destroyed every time you execute this function, and it cannot be accessed by anything other than this function.

Languages like C ++ also have block scopes ". Here, any pair of "{}" defines a new range. JScript does not support block range.

The name of a local variable can be the same as that of a global variable, but it is completely different and independent. Therefore, changing the value of a variable does not affect the value of another variable. In the function that declares a local variable, only this local variable makes sense.

Var aCentaur = "a horse with rider,"; // global definition of aCentaur.

// JScript code, which is omitted for the sake of conciseness.
Function antiquities () // declare a local aCentaur variable in this function.
{

// JScript code, which is omitted for the sake of conciseness.
Var aCentaur = "A centaur is probably a mounted Scythian warrior ";

// JScript code, which is omitted for the sake of conciseness.
ACentaur + = ", misreported; that is,"; // Add to local variable.

// JScript code, which is omitted for the sake of conciseness.
} // The function ends.

Var nothinginparticipant ular = antiquities ();
ACentaur + = "as seen from a distance by a naive innocent .";

/*
In the function, the value of this variable is "A centaur is probably a mounted Scythian warrior,
Misreported; that is, "; outside the function, the value of this variable is the rest of this sentence:
"A horse with rider, as seen from a distance by a naive innocent ."
*/
It is important to note whether the variable is declared at the beginning of its scope. Sometimes this can lead to unexpected situations.

Tweak ();
Var aNumber = 100;
Function tweak (){
Var newThing = 0; // explicitly declare the newThing variable.

// This statement assigns undefined variables to newThing because there is a local variable named aNumber.
NewThing = aNumber;

// The next statement assigns the value 42 to the local aNumber. ANumber = 42;
If (false ){
Var aNumber; // This statement will never be executed.
ANumber = 123; // This statement will never be executed.
} // The Condition Statement ends.

} // The Function Definition ends.
When JScript runs a function, it first looks for all the variable declarations,

Var someVariable;
Create a variable with an undefined initial value. If a variable has a value declared,

Var someVariable = "something ";
The variable is still initialized with an undefined value, and the declared value is replaced only when the declared row is run, if it has been declared.

JScript pre-processes the variable declaration before running the code. Therefore, it does not matter whether the declaration is in a condition block or in some other structures. JScript finds all the variables and immediately runs the code in the function. If the variable is explicitly declared in the function? That is to say, if it appears on the left of the value assignment expression but does not use var declaration? Then it is created as a global variable.
Copy, transfer, and compare data
In JScript, data processing depends on the data type.

Compare by value and by reference
Values of the Numbers and Boolean types (true and false) are copied, transmitted, and compared by value. When copying or passing by value, a space will be allocated in the computer memory and the original value will be copied to it. Then, even if you change the original value, the copied value is not affected (in turn), because these two values are independent entities.

Objects, arrays, and functions are copied, transferred, and compared by reference. When copying or passing by address, you actually create a pointer to the original item and use the pointer just like copying. If you subsequently change the original item, both the original item and the copy item will be changed (the same way in turn ). In fact, there is only one entity. A "copy" is not a real copy, but a reference to the data.

When comparing by reference, to make the comparison successful, the two variables must refer to the exact same entity. For example, two different Array objects are not equal even if they contain the same elements. To be successful, one of the variables must be another reference. To check whether two arrays contain the same elements, compare the results of the toString () method.

Finally, strings are copied and transmitted by reference, but compared by value. Note that if there are two String objects (created using new String ("something"), compare them by reference. However, if either or both of them are String values, compare them by value.

Note that given the ASCII and ANSI character set constructor, uppercase letters are placed before lowercase letters in sequence. For example, "Zoo" is smaller than "aardvark ". To perform case-insensitive matching, you can call toUpperCase () or toLowerCase () for the two strings ().

PASS Parameters to Functions
Passing a parameter to a function by value is an independent copy of the parameter, that is, a duplicate that only exists in the function. Even if you pass objects and arrays by reference, if you directly overwrite the original value with a new value in the function, the new value is not reflected outside the function. It can only be seen outside the function when the attributes of the object or the elements of the array change.

For example (using the IE Object Mode ):

// This code segment destroys (overwrites) its parameters, so
// The Call Code does not reflect any changes.
Function Clobber (param)
{
// Destroy the parameter. In the call code
// You cannot see it.
Param = new Object ();
Param. message = "This will not work ";
}

// This code changes the parameter attributes,
// You can see the property change in the call code.
Function Update (param)
{
// Change the attributes of an object;
// You can see the changes in the call code.
Param. message = "I was changed ";
}

// Create an object and assign it to an attribute.
Var obj = new Object ();
Obj. message = "This is the original ";

// Call Clobber and output obj. message. Note that it does not change.
Clobber (obj );
Window. alert (obj. message); // still displays "This is the original ".

// Call Update and output obj. message. Note that it has been changed.
Update (obj );
Window. alert (obj. message); // display "I was changed ".
Test Data
When performing a value-based test, two distinct items are compared to see if they are equal. Generally, this comparison is performed by byte. When checking by reference, it is to see whether the two items are pointers to the same original item. If yes, the comparison result is equal. If not, the comparison result is not equal even if each byte contains the same value.

Copying and passing strings by reference saves memory. However, the strings cannot be changed after they are created, so they can be compared by value. In this way, you can check whether two strings contain the same content, even if they are completely generated independently.
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.