Advanced features and special objects in JavaScript

Source: Internet
Author: User
Tags empty encode string error code eval execution numeric value string variable
Javascript| Object | advanced

  First, write the constructor

You can use the new operator to combine predefined constructors such as Object (), Date (), and function () to create and initialize an object. The powerful feature of object-oriented programming is the ability to define custom constructors to create custom objects that are used in scripts. A custom constructor is created so that an object with the defined property can be created. The following is an example of a custom function (note the use of this keyword).

function Circle (Xpoint, Ypoint, radius) {
This.x = Xpoint; x coordinate of center
This.y = Ypoint; Y-coordinate of the center
THIS.R = radius; Radius of the Circle
}

When the Circle constructor is invoked, the value of the center point and the radius of the circle are given (all of these elements are necessary to fully define a unique circular object). At the end of the Circle object contains three properties. Here's how to sample the Circle object.

var acircle = new Circle (5, 11, 99);

  Second, use prototypes to create objects

When writing a constructor, you can create inherited properties and shared methods by using properties of a prototype object that is itself a property of all constructors. The prototype properties 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 a prototype property in one object, and the new value will overwrite the default value, but it is only valid in that 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; Calculate the area of a circle
}
Circle.prototype.area = Acirclesarea; A function that calculates the area of a circle is now a method of Circle Prototype objects
var a = Acircle.area (); This is how to call an area function on a Circle object

With this principle, you can define additional properties for predefined constructors (all with prototype objects). For example, if you want to be able to delete the front and back spaces of a string (similar to the Trim function in VBScript), you can create your own method for the string prototype object.

Add a function called trim as
A method of the prototype object of the String constructor.
String.prototype.trim = function () {
Return This.replace (/(^\s*) | (   \s*$)/g, ""); Use regular expressions to place before and after spaces
}
var s = "Leading and trailing spaces"; A string with a space
Window.alert (S + "(" + s.length +) ");
s = S.trim (); Remove before and after spaces
Window.alert (S + "(" + s.length +) ");

  Third, special objects, properties and methods

Error object: Saves information about the error.

var newerrorobj = new Error ()
var newerrorobj = new Error (
Number
)
var newerrorobj = new Error (
Number
Description
)

The constructor syntax for the Error object has the following sections:

Parameters:-number. Numeric value associated with the error. If omitted, it is zero.
-description. A short string that describes the error. If omitted, it is an empty string.

Note: Whenever a run-time error occurs, an instance of the error object is generated to describe the error. The instance has two intrinsic properties that hold the description of the error (the Description property) and the error number (numbers property).

The error number is a 32-bit value. The high 16-digit word is the device code, and the low word is the actual error code.

The Error object can also be explicitly created with the syntax shown above, or thrown out with a throw statement. In both cases, you can add any attributes you choose to expand the ability of the Error object.

Typically, a local variable created in a Try...catch statement refers to an implicitly created Error object. Therefore, you can use the error number and description in any method you choose.

The following example shows the use of implicitly creating an Error object:

try {
x = y; An error has occurred.
catch (E) {//Create local variable E.
Response.Write (e)//print "[Object Error]".
Response.Write (E.number & 0xFFFF)//print 5009.
Response.Write (e.description)//print "' Y ' is undefined".
}

function objects: creating new functions.

Syntax 1

function functionname ([argname1 [, ... [, Argnamen]]] {
Body
}

Syntax 2

functionname = new Function ([Argname1, [... argnamen,]] body);

Parameters:-functionname. Required option. The name of the most recently created function
-argname1...argnamen. Options available. The list of parameters that the function receives.
-body. Options available. A string containing the JScript code block that was executed when the function was called.

Description: The basic data type in the function JScript. Syntax 1 creates a function value that is converted by JScript to a function object, if necessary. JScript converts a function created with Syntax 2 to a Fnction object when calling a function.

Syntax 1 is the basic method of creating functions in JScript. Syntax 2 is another way to explicitly create a function object.

For example, to create a function that adds the two parameters that will be passed to it, you can do either of these two methods:

Example 1

function add (x, y) {
return (x + y); Performs the addition and returns the result.
}

Example 2

var add = new Function ("X", "Y", "Return (X+y)");

In both cases, the function can be called with the following line of code:

Add (2, 3);

Note When calling a function, be sure to include the parentheses and the required arguments. Calling a function without parentheses causes the return function's text instead of the result of the function execution.

Object objects: Provides functionality that is common to all JScript objects.

obj = new Object ([value])

Parameters:-obj. Required option. The name of the variable to assign to the object.
-value. Options available. Any kind of JScript base data type. (number, Boolean, or String.) If value is an object, returns the object that is not changed. If value is null, undefined, or is not given, an object without content is generated.

Description: Object objects are included in all other JScript objects, and their methods and properties are available in all other objects. These methods can be redefined in user-defined objects and called through JScript at the appropriate time. The ToString method is an example of an Object method that is often redefined.

Arguments property: Returns a arguments object for the currently executing function object.

Function.arguments

The function argument is the name of the currently executing function and can be omitted.

Description: A function can handle a variable number of arguments through the arguments property. The length property of the arguments object contains the number of arguments passed to the function. For a single parameter contained in a arguments object, the access method is the same as the access method of the parameters contained in the array.

Example: The following example illustrates the use of the Arguments property:

function Argtest () {
var i, s, Numargs = Arguments.length;
s = Numargs;
if (Numargs < 2)
S + + "argument is passed to Argtest. It was ";
Else
s + + "arguments were passed to argtest. They were ";
for (i = 0; i < Numargs; i++) {
s + + arguments[i] + "";
}
return (s);
}

Callee property: Returns the function object that is being executed, which is the body of the specified function object.

[function.] Arguments.callee

The optional function parameter is the name of the function object that is currently executing.

Description: The Callee property is a member of the arguments object and is available only if the related function is executing.

The initial value of the Callee property is the Function object that is being executed. This allows anonymous recursive functions.

Example:

function factorial (n) {
if (n <= 0)
return 1;
Else
return n * Arguments.callee (n-1)
}
Print (factorial (3));

Requirements: version 5.5 or above.

Caller property: Returns a reference to a function that calls the current function.

Functionname.caller

The FunctionName object is the name of the function being executed.

Note: For functions, the caller property is defined only when the function executes. If the function is called by the top level of a JScript program, then caller contains null.

If you use the Caller property in the string context, the result is the same as functionname.tostring, that is, the inverse compiled text of the function is displayed.

The following example illustrates the use of the caller property:

function Calllevel () {
if (Calllevel.caller = null)
Return ("Calllevel is called from");
Else
Return ("Calllevel is called by another function.");
}

Constructor property: Represents a function that creates an object.

Object.constructor

The required object is the name of the objects or functions.

Description: The constructor property is a member of all objects that have prototype. They include all of the JScript intrinsic objects except the Global and Math objects. The constructor property holds a reference to a function that constructs a particular object instance.

For example:

x = new String ("Hi");
if (X.constructor = = String)//To be processed (condition is true).
Or
function MyFunc {
function body.
}
y = new MyFunc;
if (Y.constructor = = MyFunc)//To be processed (condition is true).

Description property: Returns or sets a description string that is associated with a specific error.

object.description [= stringexpression]

The syntax components of the Description property are as follows:

Parameters:-object. Required option. Any instance of the Error object.
-stringexpression. Options available. A string expression that contains the description of the error.

Description: The Description property contains an error message string that is associated with a particular error. Use the value contained in this to warn the user that an error has occurred that cannot or will not be handled.

Prototype property: Returns a reference to the object type prototype.

Objectname.prototype

The objectname parameter is the name of the object.

Description: Provides a set of basic functions for an object's class with the prototype property. The operation of the new instance of the object, "inherit", gives the object a prototype.

For example, to add a method that returns the maximum element value in an array for the array object. To do this, declare the function, add it to the Array.prototype, and use it.

function Array_max () {
var i, max = this[0];
for (i = 1; i < this.length; i++) {
if (Max < this[i])
max = This[i];
}
return Max;
}
Array.prototype.max = Array_max;
var x = new Array (1, 2, 3, 4, 5, 6);
var y = X.max ();

After the code executes, Y saves the maximum value in the array x, or says 6.

All JScript intrinsic objects have read-only prototype properties. You can add functionality to the prototype as in this example, but the object cannot be given a different prototype. However, user-defined objects can be assigned to a new prototype.

Apply method: Apply One method of an object and replace the current object with another object.

Apply ([Thisobj[,argarray]])

Parameters:-thisobj. Options available. The object that will be used as the current object.
-argarray. Options available. An array of arguments to be passed to the function.

Note: If Argarray is not a valid array or is not a arguments object, it will result in a typeerror.

If you do not supply any of the Argarray and thisobj parameters, the Global object will be used as a thisobj and cannot be passed any parameters.

Requirements: version 5.5 or above.

Call method: Invokes one of the object's methods to replace the current object with another object.

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]

Parameters:-thisobj. Options available. The object that will be used as the current object.
-arg1, Arg2, argn. Options available. A sequence of method parameters is passed.

Description: The call method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj.

If the thisobj parameter is not supplied, the Global object is used as a thisobj.

Requirements: version 5.5 or above.

Concat Method (Array): Returns a new array, which is a combination of two or more arrays.

Array1.concat ([item1[, item2[, ...) [, Itemn]]]

Parameters:-array1. Required option. The array object to which all other arrays are to be connected.
-item1,.. ., itemn. Options available. Other items to connect to the end of Array1.

Description: The Concat method returns an Array object that contains a connection to array1 and any other items provided.

Items to add (item1 ... itemn) are added to the array in Left-to-right order. If an item is an array, add its contents to the end of the array1. If the item is not an array, it is added to the end of the array as a single array element.

The following is a copy of an element from the source array to the result array:

For object parameters copied from the array being connected to the new array, the same object is still pointed to after replication. Whatever changes in the new array and source array will cause another change.

For a numeric or string connection to a new array, only its value is copied. A change in the value of an array does not affect the value in the other array.

Example: The following example illustrates the use of the Concat method when using an array:

function Concatarraydemo () {
var A, B, C, D;
A = new Array (1,2,3);
b = "JScript";
c = new Array ("VBScript");
D = A.concat (b, c); Returns an array of [1, 2, 3, JScript, "," VBScript "]
return (d);
}

Escape method: Encode String objects so that they can be readable on all computers.

Escape (charstring)

The required charstring parameter is any String object or literal that you want to encode.

Description: The Escape method returns a string value containing the charstring content (Unicode format). All spaces, punctuation, accented symbols, and other non-ASCII characters are replaced with%xx encodings, where xx equals the hexadecimal number that represents the character. For example, a space returns "%20".

Characters with a value greater than 255 are stored in%UXXXX format.

Note: The escape method cannot be used to encode a Uniform Resource Identifier (URI). The encodeURI and encodeURIComponent methods should be used for encoding.

Unescape method: Decodes a String object encoded using the Escape method.

Unescape (charstring)

The required charstring parameter is the String object to decode.

Description: The Unescape method returns a string value containing the charstring content. All characters encoded in%XX 16 are replaced with the medium-priced characters of the ASCII character set.

Characters encoded in%UXXXX format (Unicode characters) are replaced with Unicode characters in hexadecimal-encoded XXXX.

Note: The Unescape method cannot be used to decode a Uniform Resource Identifier (URI). The decodeURI and decodeURIComponent methods can be used to solve the code.

Eval method: Check JScript code and execute.

Eval (codestring)

Required codestring parameter is a string value that contains valid JScript code. This string will be parsed and executed by the JScript parser.

Description: The eval function allows for dynamic execution of JScript source code. For example, the following code creates a new variable mydate that contains a Date object:

Eval ("var mydate = new Date ();");

The context passed to the Eval method's execution is the same as the call to the Eval method.

encodeURI method: Encodes a text string into a valid Uniform Resource Identifier (URI).

encodeURI (uristring)

The required uristring parameter represents an encoded URI.

Description: The encodeURI method returns an encoded URI. If you pass the encoding result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: ":", "/", ";" and "?". Please encode these characters using the encodeURIComponent method.

Requirements: version 5.5 or above.

decodeURI method: Returns the encoded form of a Uniform Resource Identifier (URI).

decodeURI (uristring)

The necessary uristring parameter represents the value of an encoded URI.

Description: Replaces the outdated unescape method with the decodeURI method.

The decodeURI method returns a string value.

If the uristring is invalid, a urierror is generated.

Requirements: version 5.5 or above.

encodeURIComponent method: Encodes a text string into a valid component of a Uniform Resource Identifier (URI).

encodeURIComponent (encodeduristring)

The required encodeduristring parameter represents an encoded URI component.

Description: The encodeURIComponent method returns an encoded URI. If you pass the encoding result to decodeURIComponent, the original string is returned. Because the encodeURIComponent method encodes all characters, note that if the string represents a path, such as/folder1/folder2/default.html, the slash will also be encoded. This will not be valid when the encoding result is sent as a request to the Web server. If the string contains more than one URI component, use the encodeURI method to encode it.

Requirements: version 5.5 or above.

decodeURIComponent method: Returns the non-encoded form of a coded component of a Uniform Resource Identifier (URI).

decodeURIComponent (encodeduristring)

The required encodeduristring parameter represents an encoded URI component.

Description: Uricomponent is part of a complete URI.

If the encodeduristring is invalid, a urierror is generated.

Requirements: version 5.5 or above.

For...in statement: Executes one or more statements that correspond to each element of an object, or an array.

for (variable in [object | array])
Statements

Parameters:-variable. Required option. A variable that can be either a property of object or any element of an array.
-object, Array. Options available. The object or array to traverse on.
-statement. Options available. One or more statements to be executed relative to each attribute of object or to each element of the array. Can be a compound statement.

Description: Before each iteration of the loop, variable is assigned the next attribute of object or the next element of array. It can then be used in any statement within the loop, as if it is using the property of object or the element of the array.

When iterating over an object, there is no way to determine or control the order in which the members of the object are assigned to the variable. The iteration is executed within the array in the order of the elements, that is, 0, 1, 2 、......

Example: The following example illustrates the use of a for ... in statement, which uses an object as a federated array:

function Forindemo () {
var A, key, S = ""; Create some variables
A = {"A": "Athens", "B": "Belgrade", "C": "Cairo"}//Initialization object
For (key in a) {//Iteration properties
s + + A[key] + "
";
}
return (s);
}

Join method: Returns a string value that contains all the elements of an array that is connected together, separated by the specified delimiter.

Arrayobj.join (separator)

Parameters:-arrayobj. Required option. The Array object.
-separator. Required option. is a string object that acts as a separator between the elements of an array in the final String object. If this argument is omitted, the array elements are separated by a comma.

Note: If an element in an array is not defined or NULL, it is treated as an empty string.

Example: The following example illustrates the use of the Join method.

function Joindemo () {
var a, B;
A = new Array (0,1,2,3,4);
b = A.join ("-");
return (b);
}

Pop method: Moves the last element in the divisor group and returns the element.

Arrayobj.pop ()

The required arrayobj reference is an Array object.

Note: If the array is empty, then the undefined is returned.

Requirements: version 5.5 or above.

Push method: Adds a new element to an array and returns the new length value of the array.

Arrayobj.push ([Item1 [item2 [...] [Itemn]]])

Parameters:-arrayobj. Required option. An Array object.
-item, Item2,... itemn. Options available. The new element of the Array.

Description: The push method adds these elements in the order in which the new elements appear. If one of the arguments is an array, the array is added as a single element to the arrays. If you want to merge elements from two or more arrays, use the Concat method.

Requirements: version 5.5 or above.

Reverse method: Returns an Array object in which the order of elements is reversed.

Arrayobj.reverse ()

The required option Arrayobj parameter is an Array object.

Description: The reverse method reverses the position of an element in an Array object. During execution, this method does not create a new Array object.

If the array is not contiguous, the reverse method creates an element in the array to populate the interval in the array. The value of all the elements created by this is undefined.

Example: The following example illustrates the use of the reverse method:

function Reversedemo () {
var a, l; Declare a variable.
A = new Array (0,1,2,3,4); Creates an array and assigns a value.
L = A.reverse (); Reverses the contents of an array.
return (L); Returns an array of results.
}

Slice method (Array): Returns a section of an array.

Arrayobj.slice (start, [end])

Parameters:-arrayobj. Required option. An Array object.
-start. Required option. The starting element of the part specified in Arrayobj is the zero-based subscript.
-end. Options available. The end element of the part specified in Arrayobj is the zero-based subscript.

Description: The slice method returns an Array object that contains the specified portion of the arrayobj.

The slice method is copied to the element specified by end, but does not include the element. If start is negative, it is the length + start processing, where length is the size of the array. If end is negative, it is treated as length + end where length is the length of the array. If End is omitted, the slice method is copied to the ending of arrayobj. If End appears before start, no elements are copied into the new array.

Example: In the following example, all elements in the myarray are copied to the NewArray except for the last element:

NewArray = Myarray.slice (0,-1)

Shift method: Moves the first element in the divisor group and returns the element.

Arrayobj.shift ()

The required arrayobj reference is an Array object.

Description: The shift method moves the first element in an array and returns the element.

Requirements: version 5.5 or above.

Unshift method: Inserts the specified element into the beginning of the array and returns the array.

Arrayobj.unshift ([item1[, item2 [, ...] [, Itemn]]]

Parameters:-arrayobj. Required option. An Array object.
-item1, item2,.. ., itemn. Options available. The element that will be inserted at the beginning of the Array.

Description: The Unshift method inserts these elements into the beginning of an array, so these elements appear in the order in the sequence of arguments in the array.

Requirements: version 5.5 or above.

Splice method: Removes one or more elements from an array and, if necessary, inserts a new element at the position of the removed element, returning the removed element.

Arrayobj.splice (Start, DeleteCount, [item1[, item2[, ...) [, Itemn]]]

Parameters:-arrayobj. Required option. An Array object.
-start. Required option. Specifies that the starting position of the element is removed from the array, which is calculated starting at 0.
-deletecount. Required option. The number of elements to remove.
-item1, item2,.. ., itemn. Required option. The new element to insert at the location of the removed element.

Description: The Splice method can modify arrayobj by removing the specified number of elements starting from the start position and inserting new elements. The return value is a new Array object that consists of the removed element.

Requirements: version 5.5 or above.



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.