JavaScript Object-oriented basis (II)

Source: Internet
Author: User

One: Defining a class in a way that defines a function
In object-oriented thinking, one of the core concepts is class. A class represents an abstraction of a thing of a similar nature, and by instantiating a class, one instance of the class, the object, can be obtained.
The methods for defining a class in JavaScript are as follows:
function Class1 () {
Definition and constructors of class members
}
Here Class1 is both a function and a class. It can be understood as the constructor of a class and is responsible for initializing the work.


Second: Use the new operator to get an instance of a class
New Date ();

Represents the creation of a Date object, and date is the class that represents the date, except that the class is provided internally by JavaScript, not user-defined.
The new operator is not only valid for the inner class, but also for user-defined classes.
function Class1 () {
Definition and constructors of class members
}
var obj1=new Class1 ();
Throw away the concept of class, from the form of code, Class1 is a function, then is not all functions can be used with new to operate it? Yes, in JavaScript, functions and classes are a concept, and when a new operation is performed on a function, an object is returned. If the class member is not initialized in this function, then an empty object is returned. For example:
Define a Hello function
function Hello () {
Alert ("Hello");
}
Get an object from a new function
var obj=new hello ();
Alert (typeof (obj));
From the running result, the Hello function is executed, and obj obtains a reference to an object. When new is a function, this function is the constructor of the class represented, where the code is considered to initialize an object. The function used to represent a class is also known as a constructor.



Three: Use square brackets ([]) to refer to the properties and methods of an object

In JavaScript, each object can be thought of as a collection of multiple properties (methods), and referencing a property (method) is simple, such as:
Object name. Property (method) name
You can also refer to it in square brackets:
Object Name [Property (method) name]
Note that the method name and property name here are a string, not the original point (? identifier, for example:
var arr=new Array ();
Add an element to an array
Arr.push ("abc");
arr["Push"] ("abc");
Get the length of the array
var len=arr.length;
var len=arr["Length"];
The length of the output array
alert (len);

Thus, the above code is equivalent to:
var arr=new Array ();
Add an element to an array
Arr.push ("abc");
Get the length of the array
var len=arr.length;
The length of the output array
alert (len);
This type of reference attribute (method) is similar to the array, which embodies the nature of a set of properties (methods) of a JavaScript object.
This usage is appropriate for situations where you are unsure of which property (method) to refer to, such as an object that represents a user profile, and a string that represents the attribute to be used, which can be referenced in this way:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Defines a user class that includes two member age and sex, and specifies the initial value.
function User () {
this.age=21;
this.sex= "Male";
}
Creating a User Object
var user=new user ();
Display the user's information based on a drop-down list box
Function Show (SLT) {
if (slt.selectedindex!=0) {
Alert (User[slt.value]);
}
}
-
</script>
<!--drop-down list box to select User Information--
<select onchange= "Show (This)" >
<option> Please select the information you need to see:</option>
<option value= "Age" > Ages </option>
<option value= "Sex" > Sex </option>
</select>
In this code, a drop-down list box is used to let the user choose which information to view, and the value of each option represents the property name of the user object. If you do not use square brackets in this way, you can do so using the following code:
Function Show (SLT) {
if (slt.selectedindex!=0) {
if (slt.value== "age") alert (user.age);
if (slt.value== "sex") alert (user.sex);
}
}
Instead, use the square brackets syntax to write:
Alert (User[slt.value]);
The square brackets syntax is like a parameter syntax, and you can use a variable to represent which property of the referenced object. If you do not use this method and do not want to use conditional judgment, you can use the Eval function:
Alert (eval ("User.") +slt.value));
This takes advantage of the nature of the Eval function, executes a dynamically generated code, and returns the result.
In fact, when you refer to the collection object of document earlier, there is a use like square brackets, such as referencing a form object named "Theform" in the page that was previously used:
document.forms["Theform"];
can also be rewritten as:
Document.forms.theForm;
The forms object is an internal object, and unlike a custom object, it can also use an index to refer to one of its properties.

<script type= "Text/javascript" >        //The result of these two writing outputs is a consistent        var arr=new Array ();  Arr.push ("ABCD");        arr["Push"] ("ABCD")            alert (arr);       alert (arr.length);        Alert (arr["Length"]);    </script>
functionShow (SLT) {
if (Slt. Selectedindex== alert (user[slt.value]);
var value=eval (+slt. value);
alert (value);
alert (eval ( "user." +slt. value));
} /span> </script>

Three: Dynamically add, modify, delete properties and methods of objects

Have learned how to reference an object's properties and methods
In other languages, once an object is generated, it cannot be changed, and to add or modify a member for an object must be modified in the corresponding class, re-instantiated, and the program must be recompiled. JavaScript provides a flexible mechanism to modify the behavior of objects, adding, modifying, and deleting properties and methods on the fly. For example: Create an empty object user with class object first:
var user=new Object ();
1. Add Property
At this point the User object has no properties and methods, and you can add properties dynamically for it, for example:
User.name= "Jack";
user.age=21;
user.sex= "Male";
With the above statement, the user object has three properties: Name, age, and sex. The following outputs these three statements:
alert (User.Name);
alert (user.age);
alert (user.sex);
The result of running the code shows that three properties are completely owned by the user object.
2. Add method
The procedure for adding a method is similar to adding a property:
User.alert=function () {
Alert ("My name is:" +this.name);
}
This adds a method "alert" to the user object, which, by executing it, pops up a dialog box to display its name:
User.alert ();
?
3. modifying properties and Methods
The process of modifying a property and method is to replace the old property with the new one, for example:
User.name= "Tom";
User.alert=function () {
Alert ("Hello," +this.name);
}
This modifies the value of the user object's Name property and the alert method, which changes from displaying the My name is dialog box to displaying the Hello dialog box.
4. deleting properties and methods
The process of deleting a property and method is also simple, which is to set it to undefined:
user.name=undefined;
user.alert=undefined;
This removes the name attribute and the alert method.
Or
Delete User.Name;
When you add, modify, or delete an attribute, you can also use the square brackets ([]) syntax when the property is the same as the reference property:
user["Name"]= "Tom";
Another feature of this approach is that you can use a non-identifier string as the property name, for example, the identifier does not allow a number to begin with or a space, but it can be used in square brackets ([]) syntax:
user["My Name"]= "Tom";
It is important to note that the square brackets syntax is still used to refer to a property that uses this non-identifier as its name:
Alert (user["my Name"]);
and cannot be written as:
Alert (user.my name);
In fact, every object in JavaScript is dynamically variable, which gives programming flexibility and distinguishes it from other languages.


Tip: The difference between undefind and null: undefined undefind defines null not found;

Remember: JS is not overloaded,

Five: Create untyped objects using curly braces ({}) syntax

In a traditional object-oriented language, each object corresponds to a class. As mentioned in this pointer, the object in JavaScript is actually a collection of attributes (methods) and does not have the concept of class in a strict sense. So it provides a simple way to create an object, the curly brace ({}) Syntax:
{
Property1:statement,
Property2:statement2,
...,
Propertyn:statmentn
}
By enclosing multiple properties or methods with braces and their definitions (these properties or methods are separated by commas) to implement the definition of an object, the code directly defines an object with n properties or methods, where the property name and its definition are separated by a colon (:). For example:
<script language= "JavaScript" type= "Text/javascript" >
<!--
var obj={}; An empty object was defined
var user={
Name: "Jack",//defines the Name property and initializes it to Jack
favoritecolor:["Red", "green", "black", "white"],//defines a color preference array
Hello:function () {//defines the method hello
Alert ("Hello," +this.name);
},
Sex: "Male"//defines sex attribute sex, initialized to male
}
Method of invoking the user object Hello
User.hello ();
-
</script>
The first line defines an untyped object, obj, which is equivalent to:
var obj=new Object ();
It then defines an object user and its properties and methods. Note that except for the last attribute (method) definition, the others must end with a comma (,). In fact, the use of dynamic increment and decrement properties can also define an identical user object, which can be implemented using the method described earlier.
You can also use a string as a property (method) name in this way to define an object, for example:
var obj={"001": "ABC"}
This defines an attribute "001" for the object obj, which is not a valid identifier, so reference to this property must use the square bracket syntax:
obj["001"];
Thus, untyped objects provide an easy way to create objects that represent an object as a complete entity in a compact and clear syntax. It also helps to reduce the size of the code, which is especially important for JavaScript code, and reducing the volume means faster access.

VI: Prototype prototype object (can be understood as static property)

Prototype object is an important mechanism to implement object-oriented. Each function is actually an object, and their corresponding class is "function", but their identities are special, each function object has a sub-object prototype. That is, prototype represents the prototype of the function, and the function is also a class, and prototype is a collection of members representing a class. When you get an object of a class by using new, the members of the prototype object become members of the instantiated object.
Since prototype is an object, give a simple example:
Defines an empty class
function Class1 () {
Empty
}
Modify the prototype object of the class to add method
Class1.prototype.method=function () {
Alert ("It ' s a test method");
}
To create an instance of a class Class1
var obj1=new Class1 ();
Method of calling Obj1
Obj1.method ();


Define a JS file:

function User () {    this.age = +;    THIS.name = "Zhang San"}

  <script type= "Text/javascript" src= "js/demo01.js" ></script> function Test7 () {            var user01 = new User ();            user01.name = "Zhangsan";                        Defining a prototype  will have this zodiac            user.prototype.alert=function () {                alert ("User alert111")            }            User01.alert ();            var user02 = new User ();                   User02.alert ();            var user03 = new User ();            User03.alert ();        }

<button onclick= "Test7 ()" >Test7</button>

JavaScript Object-oriented basis (II)

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.