03 advanced JScript

Source: Internet
Author: User
Create advanced object use constructor to create object

A constructor is a function that calls it to demonstrate and initialize special types of objects. Available
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 Date Object.
var myCar = new Car();                   // Create a User-Defined Object and initialize its attributes.

Use the constructor to take a parameter as a specificThisThe value of the keyword is passed to the newly created empty 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

AvailableNewOperator combinationObject (),Date ()And
Function ()This predefined constructor creates an object and initializes it. 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:This
Keyword ).

function Circle (xPoint, yPoint, radius) {
    this.x = xPoint;  // Center x Coordinates.
    this.y = yPoint;  // Center y Coordinates.
    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:
ThisKeyword ).

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 used to calculate the circular area is Circle Prototype Object.
var a = ACircle.area();               // How Circle Call the area function on the object.

With this principle, you can define additional attributes for pre-defined Constructors (all with prototype objects. For example, if you want to delete the leading and trailing spaces of a string (
TrimFunction), you canStringCreate your own method for the prototype object.

// Add trim Function
// String A Method of the prototype object of the constructor.
String.prototype.trim = function()
{
    // Use a regular expression to separate spaces
    // Use a null string.
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
 
// String with spaces
var s = "    leading and trailing spaces    ";
 
// Display "    leading and trailing spaces     (35)"
window.alert(s + " (" + s.length + ")");
 
// Remove leading and trailing Spaces
s = s.trim();
// Display"leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");

 

 

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.

Recursion and iteration are closely related-algorithms that can be processed by recursion can also adopt iteration, 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.

}

 

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 mountedscythian 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 naiveinnocent .";

 

/*

In the function, the value of this variable is "a Centaur is probably a mountedscythian 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 anaive 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 ){

Varanumber; // 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, if it appears on the left of the value expression but does not use VaR Declaration-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 (TrueAnd
False) Is 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 differentArrayObjects that contain the same elements are not equal. To be successful, one of the variables must be another reference. To check whether two arrays contain the same elements, compareTostring ()Result of the method.

Finally, strings are copied and transmitted by reference, but compared by value. Note that if there are twoStringObject (Use
NewString ("something"), compare them by reference. However, if one or both of them are string values, compare them by value.

Note: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 callTouppercase ()Or
Tolowercase ().

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 = newobject ();

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.

 

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.