[Recommended] basic tutorial on javascript Object-Oriented Technology

Source: Internet
Author: User

As a result, after reading it for a long time, I had a rough understanding and had a good aftertaste. It seems that I didn't understand anything...
This article is written in chapter 7, 8 and 9 of <javascript-the definitive guide, 5th edition>.
The javascript object-oriented technology (Object/array-> function-> class/constructor/prototype) will be explained according to the structure of the original book as much as possible ). I will attach the original English statement for your reference.
If no description is provided, all the English statements (except the program body) in the text are derived from <javascript-the definitive guide, 5th edition>.
-------------------------------------------------
Objects and Arrays (Objects and Arrays)
What is an object? Put a combination of "name-attribute" in a unit to form an object. We can understand it as javascript.
The object is a set of "key-value" pairs (An object is a collection of named values. These named values are usually referred
To as properties of the object. -- Section3.5 ).
"Name" can only be string type, not other type, and the attribute type is
Any (number/string/other Object...) .. you can use new Object () to create an empty Object. You can also use "{}" to create an empty Object.
Empty object. The two functions are equivalent.
Copy codeThe Code is as follows:
Var emptyObject1 ={}; // create an empty object
Var emptyObject2 = new Object (); // create an empty Object
Var person = {"name": "sdcyst ",
"Age": 18,
"Sex": "male"}; // create an object with an initial value, person
Alert (person. name); // sdcyst
Alert (person ["age"]); // 18

From the above example, we can also see that accessing the attributes of an object can simply add ". you can use the "[]" operator to obtain the attribute name after adding it. In this case, the attribute name in [] must be enclosed by quotation marks, because indexes in the object are of the string type. the number of attributes in an object is variable. After an object is created, you can assign any attributes to it at any time.
Copy codeThe Code is as follows:
Var person = {};
Person. name = "sdcyst ";
Person ["age"] = 18;
Alert (person. name + "_" + person. age); // sdcyst _ 18
Var _ person = {name: "balala", "age": 23}; // when constructing an object, the attribute name can be marked without quotation marks (name ),
// But it is still a string type. quotation marks are still required in [] during access.
Alert (_ person ["name"] + "_" + person. age); // balala _ 23
Alert (_ person [name]); // undefinied
Var person = {};
Person. name = "sdcyst ";
Person ["age"] = 18;
Alert (person. name + "_" + person. age); // sdcyst _ 18
Var _ person = {name: "balala", "age": 23}; // when constructing an object, the attribute name can be marked without quotation marks (name ),
// But it is still a string type. quotation marks are still required in [] during access.
Alert (_ person ["name"] + "_" + person. age); // balala _ 23
Alert (_ person [name]); // undefinied

When you use the "." operator to get the object attributes, you must know the attribute name. Generally, the "[]" operator has more powerful functions to get object attributes,

You can add some expressions in [] to get the attribute value,
For example, it can be used in loop control statements, but the "." operator does not have this flexibility.
Copy codeThe Code is as follows:
Var name = {"name1": "NAME1", "name2": "NAME2", "name3": "NAME3", "name4": "NAME4 "};
Var namestring = "";
For (var props in name) {// attribute name in the loop name object
Namestring + = name [props];
}
Alert (namestring); // NAME1NAME2NAME3NAME4

Namestring = "";
For (var I = 0; I <4; I ++ ){
Namestring + = name ["name" + (I + 1)];
}
Alert (namestring); // NAME1NAME2NAME3NAME4

The delete operator can delete an attribute of an object and determine whether a property exists. The "in" operator can be used.
Copy codeThe Code is as follows:
Var name = {"name1": "NAME1", "name2": "NAME2", "name3": "NAME3", "name4": "NAME4 "};
Var namestring = "";
For (var props in name) {// attribute name in the loop name object
Namestring + = name [props];
}
Alert (namestring); // NAME1NAME2NAME3NAME4

Delete name. name1; // delete the name1 attribute
Delete name ["name3"]; // delete the name3 attribute
Namestring = "";
For (var props in name) {// attribute name in the loop name object
Namestring + = name [props];
}
Alert (namestring); // NAME2NAME4

Alert ("name1" in name); // false
Alert ("name4" in name); // true

Note that the attributes in the object are unordered.

Constructor attribute of the object
Each javascript Object has a constructor attribute. This attribute corresponds to the constructor during object initialization (the function is also an object ).
Copy codeThe Code is as follows:
Var date = new Date ();
Alert (date. constructor); // Date
Alert (date. constructor = "Date"); // false
Alert (date. constructor = Date); // true

Array
As we have mentioned, objects are unordered data sets, while arrays are ordered data sets. Data (elements) in arrays are accessed through indexes (starting from 0,
The data in the array can be any data type. The array itself is still an object, but due to many features of the array, the array and the object are usually different
Throughout this book, objects and arrays are often treated as distinct PES ypes.
This is a useful and reasonable simplification; you can treat objects and arrays as separate types
For most of your JavaScript programming. To fully understand the behavior of objects and arrays,
However, you have to know the truth: an array is nothing more than object with a thin layer of extra
Functionality. You can see this with the typeof operator: applied to an array value, it returns
The string "object". -- section7.5 ).
To create an Array, you can use the "[]" operator or the Array () constructor to create a new one.

Js Code
Copy codeThe Code is as follows:
Var array1 = []; // create an empty array
Var array2 = new Array (); // create an empty Array
Array1 = [1, "s", [3, 4], {"name1": "NAME1"}]; //
Alert (array1 [2] [1]); // 4 access the array elements in the array
Alert (array1 [3]. name1); // NAME1 access the object in the array
Alert (array1 [8]); // undefined
Array2 = [,]; // if no value is specified and only a comma is entered, the element at the corresponding index is undefined.
Alert (array2.length); // 3
Alert (array2 [1]); // undefined
Var array1 = []; // create an empty array
Var array2 = new Array (); // create an empty Array
Array1 = [1, "s", [3, 4], {"name1": "NAME1"}]; //
Alert (array1 [2] [1]); // 4 access the array elements in the array
Alert (array1 [3]. name1); // NAME1 access the object in the array
Alert (array1 [8]); // undefined
Array2 = [,]; // if no value is specified and only a comma is entered, the element at the corresponding index is undefined.
Alert (array2.length); // 3
Alert (array2 [1]); // undefined

When using new Array () to create an Array, you can specify a default size. The value is undefined, and you can assign values to them later.

The length of the array in javascript can be changed at will, and the content in the array can also be changed at will. Therefore, the initialization length is actually
There is no binding force on the array. For an array, If you assign a value to an index that exceeds its maximum length, the length of the array is changed, and no value is assigned to the index.
The value of the index is undefined. See the example below.

Js Code
Copy codeThe Code is as follows:
Var array = new Array (10 );
Alert (array. length); // 10
Alert (array [4]); // undefined
Array [100] = "100th"; // This operation changes the length of the array and sets the value of the 10-99 index to undefined.
Alert (array. length); // 101
Alert (array [87]); // undefined
Var array = new Array (10 );
Alert (array. length); // 10
Alert (array [4]); // undefined
Array [100] = "100th"; // This operation changes the length of the array and sets the value of the 10-99 index to undefined.
Alert (array. length); // 101
Alert (array [87]); // undefined

You can use the delete operator to delete the elements of an array. Note that this deletion only sets the elements of the array at this position as undefined, and the length of the array has not changed.

We have used the length attribute of the array. The length attribute is a read/write attribute, that is, we can change the length attribute of the array.
The length of the array is arbitrarily changed. If the length is set to a value smaller than the length of the array, the index value greater than length-1 in the original array will be deleted. If the length is
If the value is greater than the length of the original array, the value between them is set to undefined.

Js Code
Copy codeThe Code is as follows:
Var array = new Array ("n1", "n2", "n3", "n4", "n5"); // array of the Five Elements
Var astring = "";
For (var I = 0; I <array. length; I ++) {// loop array element
Astring + = array [I];
}
Alert (astring); // n1n2n3n4n5
Delete array [3]; // delete the value of an array element
Alert (array. length + "_" + array [3]) // 5_undefined

Array. length = 3; // reduce the length of the array
Alert (array [3]); // undefined
Array. length = 8; // extend the length of the array
Alert (array [4]); // undefined
Var array = new Array ("n1", "n2", "n3", "n4", "n5"); // array of the Five Elements
Var astring = "";
For (var I = 0; I <array. length; I ++) {// loop array element
Astring + = array [I];
}
Alert (astring); // n1n2n3n4n5
Delete array [3]; // delete the value of an array element
Alert (array. length + "_" + array [3]) // 5_undefined

Array. length = 3; // reduce the length of the array
Alert (array [3]); // undefined
Array. length = 8; // extend the length of the array
Alert (array [4]); // undefined

For other methods of arrays, such as join/reverse, we will not give an example here.

Through the above explanation, we know that the attribute value of an object is obtained by the attribute name (string type), while the element of the array is obtained
Reference (integer type 0 ~~ 2 ** 32-1) to get the value. The array itself is also an object, so the object attribute operation is also fully suited to arrays.

Js Code
Copy codeThe Code is as follows:
Var array = new Array ("no1", "no2 ");
Array ["po"] = "props1 ";
Alert (array. length); // 2
// For arrays, array [0] has the same effect as array ["0 (? Not sure. This is true during testing)
Alert (array [0] + "_" + array ["1"] + "_" + array. po); // no1_no2_props1


Function
Javascript functions have been written a lot, so here is a brief introduction.
Create a function:
Copy codeThe Code is as follows:
Function f (x ){........}
Var f = function (x ){......}

You can create a function named f () in either of the above two forms. However, you can create an anonymous function in the latter form.
When defining a function, you can set parameters. If the number of parameters passed to the function is insufficient, the parameters are matched from the leftmost, And the other parameters are assigned with undefined values.
More parameters than the number of function-defined parameters are ignored.



Js Code
Copy codeThe Code is as follows:
Function myprint (s1, s2, s3 ){
Alert (s1 + "_" + s2 + "_" + s3 );
}
Myprint (); // undefined_undefined_undefined
Myprint ("string1", "string2"); // stringinclustring2_undefined
Myprint ("string1", "string2", "string3", "string4"); // string1_string2_string3
Function myprint (s1, s2, s3 ){
Alert (s1 + "_" + s2 + "_" + s3 );
}
Myprint (); // undefined_undefined_undefined
Myprint ("string1", "string2"); // stringinclustring2_undefined
Myprint ("string1", "string2", "string3", "string4"); // string1_string2_string3

Therefore, for a defined function, we cannot expect the caller to pass all the parameters in. For those required parameters, they should be in the function body.
Detect (use! Operator), or set the default value, and then perform the OR (|) operation with the same parameter to obtain the parameter.



Js Code
Copy codeThe Code is as follows:
Function myprint (s1, person ){
Var defaultperson = {// default person object
"Name": "name1 ",
"Age": 18,
"Sex": "female"
};
If (! S1) {// s1 cannot be blank
Alert ("s1 must be input! ");
Return false;
}
Person = person | defaultperson; // accepts the parameter of the person object.
Alert (s1 + "_" + person. name + ":" + person. age + ":" + person. sex );
};

Myprint (); // s1 must be input!
Myprint ("s1"); // s1_name1: 18: female
Myprint ("s1", {"name": "sdcyst", "age": 23, "sex": "male"}); // s1_sdcyst: 23: male
Function myprint (s1, person ){
Var defaultperson = {// default person object
"Name": "name1 ",
"Age": 18,
"Sex": "female"
};
If (! S1) {// s1 cannot be blank
Alert ("s1 must be input! ");
Return false;
}
Person = person | defaultperson; // accepts the parameter of the person object.
Alert (s1 + "_" + person. name + ":" + person. age + ":" + person. sex );
};

Myprint (); // s1 must be input!
Myprint ("s1"); // s1_name1: 18: female
Myprint ("s1", {"name": "sdcyst", "age": 23, "sex": "male"}); // s1_sdcyst: 23: male

Arguments attribute of the Function
Each function body contains an arguments identifier, which represents an Arguments object. The Arguments object is very similar.
For example, an Array object has the length attribute. the value to be accessed uses the "[]" operator to access the parameter value. However, the two are completely different.
Things only have something in common on the surface (for example, modifying the length attribute of an Arguments object does not change its length ).

Js Code
Copy codeThe Code is as follows:
Function myargs (){
Alert (arguments. length );
Alert (arguments [0]);
}
Myargs (); // 0 --- undefined
Myargs ("1", [1, 2]); // 2 --- 1
Function myargs (){
Alert (arguments. length );
Alert (arguments [0]);
}
Myargs (); // 0 --- undefined
Myargs ("1", [1, 2]); // 2 --- 1 the Arguments object has a callee attribute that indicates the method of the current Arguments object. you can use it to implement internal recursive calls to anonymous functions.

Js Code
Copy codeThe Code is as follows:
Function (x ){
If (x <= 1) return 1;
Return x * arguments. callee (x-1 );
} (Section8.2)
Function (x ){
If (x <= 1) return 1;
Return x * arguments. callee (x-1 );
} (Section8.2)

Method -- Method
The method is a function. We know that each object contains 0 or more attributes, and the attributes can be of any type. Of course, the object is also included. The function itself is
So we can put a function into an object. At this time, this function becomes a method of the object. If you want to use this method later,
The object name can be implemented using the "." operator.

Js Code
Copy codeThe Code is as follows:
Var obj = {f0: function () {alert ("f0") ;}}; // The object contains a method
Function f1 () {alert ("f1 ");}
Obj. f1 = f1; // Method for adding an object

Obj. f0 (); // f0 f0 is the obj method.
Obj. f1 (); // f1 f1 is the obj method.
F1 (); // f1 f1 is a function and can be called directly.
F0 (); // f0 is only the obj method and can only be called through objects.
Var obj = {f0: function () {alert ("f0") ;}}; // The object contains a method
Function f1 () {alert ("f1 ");}
Obj. f1 = f1; // Method for adding an object

Obj. f0 (); // f0 f0 is the obj method.
Obj. f1 (); // f1 f1 is the obj method.
F1 (); // f1 f1 is a function and can be called directly.
F0 (); // f0 is only the obj method and can only be called through objects.

Method calls require the support of objects. How can we obtain object attributes in methods? This! We are already familiar with this keyword.
In this method, we can use this to obtain reference to the method caller (object) and obtain various attributes of the method caller.



Js Code
Copy codeThe Code is as follows:
Var obj = {"name": "NAME", "sex": "female "};
Obj. print = function () {// Add Method for Object
Alert (this. name + "_" + this ["sex"]);
};
Obj. print (); // NAME_female
Obj. sex = "male ";
Obj. print (); // NAME_male
Var obj = {"name": "NAME", "sex": "female "};
Obj. print = function () {// Add Method for Object
Alert (this. name + "_" + this ["sex"]);
};
Obj. print (); // NAME_female
Obj. sex = "male ";
Obj. print (); // NAME_male

Here is a more object-oriented example.

Js Code
Copy codeThe Code is as follows:
Var person = {name: "defaultname ",
SetName: function (s ){
This. name = s;
},
"PrintName": function (){
Alert (this. name );
}}
Person. printName (); // defaultname
Person. setName ("newName ");
Person. printName (); // newName
Var person = {name: "defaultname ",
SetName: function (s ){
This. name = s;
},
"PrintName": function (){
Alert (this. name );
}}
Person. printName (); // defaultname
Person. setName ("newName ");
Person. printName (); // newName

In the above example, you can use person. name =... to directly change the name attribute of person. Here we just want to show the content just mentioned.
Another way to change the person attribute is to define a function and receive two parameters, one being person and the other being name. It looks like this:
ChangeName (person, "newName"). which method is better? Obviously, the methods in the example are more visual and intuitive, and seem to have such a specific aspect.
Object Shadow.

Once again, the Method itself is a function, but the use of the Method is more restricted. In the subsequent sections, If we mention the function
The content mentioned also applies to methods, but not all.

Prototype attribute of the Function
Each function contains a prototype attribute, which forms the core foundation of javascript object-oriented. We will discuss it in detail later.

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.