26javascript Object-based

Source: Internet
Author: User

1. Implementing classes with JavaScript
JAVASCRITPT does not have a specialized mechanism to implement classes, here is the use of its functions to allow nested mechanisms to implement the class. A function can contain variables and can contain other functions, so that variables can be used as attributes, and internal functions can be used as member methods. So the outer function itself can be used as a class. As follows:


function MyClass ()
{
Here is equivalent to the constructor function
}
Here MyClass is a class. You can actually think of it as a constructor of a class. As for the part of the non-constructor, it will be described in detail later.


How to get an instance of a class
Implementing a class should give you an instance of the class, and JavaScript provides a way to get an object instance. That is, the new operator. In fact, in JavaScript, classes and functions are the same concept, and an object is returned when you manipulate a function with new. As follows:
var obj1 = new MyClass ();


References to members of the object
There are three ways to refer to a class's properties or methods in JavaScript.
The dot operator, which is the most common way of quoting, is not burdensome. such as the following form:
Object name. property name;
Object name. Method name;


Square brackets refer to the members of the object that are allowed to be referenced in JavaScript by square brackets. As follows:
Object name ["Property name"];
Object name ["Method name"];
Inside the square brackets is a string representing the property or method name, not necessarily a string constant. You can also use variables. This allows you to pass a property or method name using a variable. It brings convenience to programming. In some cases, it is not possible in your code to determine which property or method to invoke. Otherwise, if you use the dot operator, you also need to invoke the property or method using conditional judgment.
In addition, properties and method names that are referenced by using square brackets can also start with a number, or a space appears, and the property and method names referenced with the dot number follow the rules of the identifier. However, the use of non-identifier naming methods is not generally advocated.


If you reference a member of a non-object, the undefined is returned.

Using the Eval function
The Eval function is a good choice if you do not want to use variables to pass variables or method names, and you do not want to use conditional judgments. Eval receives a parameter of a string type, and then executes the string as code in the context, returning the result of the execution. This is where the Eval function is used. As follows:
Alert (eval ("Object name." + Element.value));//Use Eval to execute a function of an object or to get a property of an object

2 Add, modify, and delete operations on object properties, methods
The JavaScript object (an instance of object) is an unordered collection.
In JavaScript, properties and methods can be added, modified, and deleted dynamically for an object after the object is built, unlike other object-oriented languages.
Adding Properties and methods
Create an object first, without any properties and methods after the empty object is created, but we can create it in code.
var obj1 = new Object ();
Add Property
Obj1.id = 1;//or obj1[' ID ']=1;
Obj1. Name = "Johnson";//or obj1[' name ']= "Johnson"


Add method
Obj1.showmessage = function ()
{
Alert ("ID:" + this.id + ", Name:" + this.) Name);
}


modifying properties and Methods
Similar to adding properties and methods, such as the example above:
modifying properties
Obj1.id = 1;
Obj1. Name = "Amanda";


Modify method
Obj1.showmessage = function ()
{
Alert ("ID:" + this.id ");
}

deleting properties and methods
Assign the property or method you want to delete directly to undefined:
Obj1.id = 1;
Obj1. Name = undefined;


Obj1.showmessage = undefined;




3 Create untyped objects.
JavaScript can also create untyped objects. The form is as follows:
var obj1 = {};
var obj2 =
{
Id:1,
Name: "Johnson",
Showmessage:function ()
{
Alert ("ID:" + this.id + "Name:" + this.) Name);
}
}
There are two untyped objects defined here, Obj1 and Obj2. Where Obj1 is an empty object. Obj2 includes two attribute IDs, name, and a method showmessage. Each property and method is separated by commas. The attribute (method) name and its value are separated by semicolons.
When you create an attribute method in this way, you can also define the name of the property method with a string. Such as:
var obj2 =
{
"ID": 1,
"Name": "Johnson"
}

The in operator determines whether the property of an object returns False if it is not a property of the object.
For example:
var AA = {
CONST: {
Single: "Single",
MULTI: ' MULTI '
},
Include:function (type) {
Return (Type.touppercase () in this. CONST);
}
}
Alert (Aa.include (' single ')); Returns the True,include method to determine if ' single ' is an attribute in the Const object inside the object AA. The This keyword inside the Include method represents the current object AA.




3prototype
Each function object has a child object prototype, because a function can also represent a class, so prototype represents a collection of members of a class. When you new an object, the members of the prototype object are instantiated as members of the object. Let's look at an example:
function MyClass ()
{ }


MyClass.prototype.ID = 1;
MyClass.prototype.Name = "Johnson";
MyClass.prototype.showMessage = function ()
{
Alert ("ID:" + this.id + "Name:" + this.) Name);
}


var obj1 = new MyClass ();
Obj1.showmessage ();
There is a benefit to creating a class using the prototype object. If you write all the members directly in the declaration of the class, the following:
function MyClass ()
{
Add Property
This.id = 1;
This. Name = "Johnson";


Add method
This.showmessage = function ()
{
Alert ("ID:" + this.id + ", Name:" + this.) Name);
}
}


var obj1 = new MyClass ();
var obj2 = new MyClass ();
In the above code, a class MyClass is defined, and two properties and a method are defined directly in the class. Then we instantiate two objects, and here are two properties and a method, each time the MyClass object is created, the memory space is wasted. With prototype, the problem can be solved after each new function, the members of its prototype object are automatically assigned to the object, and when new multiple objects are not created repeatedly.
Since the initialization of the prototype occurs before the function body executes, it can be demonstrated by the following code:
function MyClass ()
{
Here is equivalent to the constructor function
This.id = 1;
This. Name1 = this. Name;
This.showmessage ();
}
MyClass.prototype.Name = "Johnson";
MyClass.prototype.showMessage = function ()
{
Alert ("ID:" + this.id + ", Name:" + this.) Name);
}


var obj1 = new MyClass ();
Executing the above code reveals that the dialog box pops up when the object of the new type is used.
Finally, prototype has a method that is used in object-oriented design. That is: The constructor property is a call to the constructor, where the constructor is the code in the declaration of the class mentioned above. Such as:
function MyClass ()
{
Here is equivalent to the constructor function
Alert ("This was in constructor");
}
MyClass.prototype.constructor ();


var obj1 = new MyClass ();
Execute the above code and you will notice that the dialog box pops up two times. This shows that prototype can be used exclusively for the design of members of the class, in fact, in JavaScript object-oriented design, many times will use the prototype.




4javascript Exception Handling
The following is an example of JavaScript exception handling:
<script type= "Text/javascript" >
var array = null;
try {
document.write (Array[0]);
} catch (Err) {
Document.writeln ("Error name:" + err.name + "</br>");
Document.writeln ("Error message:" + err.message);
}
finally{
Alert ("Object is null");
}
</script>
<body>


</body>
Program execution Process
ARRAY[0] The array is an empty object because the array is not created, and calling Array[0] in the program produces an object is null exception


catch (ERR) statement captures this exception by Err.name printing the error type, Err.message prints the details of the error. For example, variables or functions undefined exceptions.


Finally, a Java-like finally, whether or not an exception will be executed.


We summarize the information of the six values of Error.name:
The use of Evalerror:eval () is inconsistent with the definition
Rangeerror: Value out of bounds
Referenceerror: Illegal or unrecognized reference value
SyntaxError: Syntax parsing error occurred
TypeError: Wrong type of operand
Improper use of Urierror:uri processing functions


Throw Statement Description
The throw statement has been implemented in javascript1.4. The syntax of a try is simple, as follows throw expression;
The expression can be any type, meaning that the throw "there is a error" or throw 1001 is correct. But usually we throw an error object or subclass of the Error object. About error We'll look at the sample code for a throw before we introduce it later.
For example:
function factorial (x) {
If The input argument is invalid, throw an exception!
if (x < 0)
throw new Error ("x must not being negative");
Otherwise, compute a value and return normally
for (var f = 1; x > 1; F *= x, x--)/* empty */;
return F;
}


Error Object
The Error object and its subclasses are implemented in javascript1.5. There are two types of error constructors
New Error ()
New Error (Message)
Error has two basic properties, name and message. The message is used to represent the details of the exception. and name refers to the constructor of the error object.
In addition, different JS engines provide some extensions to the error, such as that Mozilla provides extensions for filename (the file name of the exception appears) and LineNumber (the line number of the exception), while IE provides support for number (error numbers). However, name and message are two basic properties that can be supported in both Firefox and IE. There are several subcategories of error in JavaScript evalerror, Rangeerror, Referenceerror, SyntaxError, TypeError, Urierror.




JavaScript exception handling mechanism and WINDOW.ONERROR handle
When the error in JavaScript code, the JS engine will be based on the JS call stack to find the corresponding catch, if not find the corresponding catch handler or catch handler itself with error or throw a new error, Finally, the error will be processed to the browser, the browser will be in a different way (ie in the yellow triangle pattern displayed in the lower left corner, and Firefix will appear in the error console) display error message to the visitor.


The JavaScript Window object has a special property onerror, if you assign a function to the OnError property of the window, then there is a JavaScript error in this window, The function is called, which means that the function will be the handle to the error handle of the window.
Display error messages in a dialog box, but never more than 3
Window.onerror = function (msg, URL, line) {
if (onerror.num++ < Onerror.max) {
Alert ("ERROR:" + msg + "\ n" + URL + ":" + line);
return true;
}
}
Onerror.max = 3;
Onerror.num = 0;
The onerror handle will have 3 parameters: The error message prompt, the document URL of the JavaScript that generated the error, and the line number where the error occurred.


The return value of the onerror handle is also important if the handle returns true, indicating that the browser does not need to do extra processing of the error, which means that the browser does not have to display the error message again. If False is returned, the browser will still prompt for an error message.

26javascript Object-based

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.