Javascript learning notes (2) array and object section, javascript learning notes

Source: Internet
Author: User
Tags javascript array

Javascript learning notes (2) array and object section, javascript learning notes

Javascript Object Section

I. Basics

1. All variables in JavaScript are objects, except for null and undefined.

2. Jscript supports four types of objects: internal objects, generated objects, and objects provided by the host (all BOM and DOM objects are host objects .) And ActiveX objects (external components ).

3. Microsoft Jscript provides 11 internal (or "built-in") objects. They are Array, Boolean, Date, Function, Global, Math, Number, Object, RegExp, Error, and String objects.

4. The object is only a special type of data. The object has attributes and methods. JavaScript is an object-oriented language, but JavaScript does not use classes. JavaScript is based on prototype rather than class.

5. attribute: a variable that belongs to a specific object. Method: it is a function that can only be called by a specific object.

6. A Jscript object is a set of attributes and methods. A method is a function that is a member of an object. An attribute is a value or a group of values (in the form of an array or object) and a member of an object.

7. javascript objects are based on constructors. When using constructors to create a new object, it can be said that a new object is instantiated. Attribute is the variable inside the constructor function.

Objects instantiated using constructors:

Cat = new Animal ();
8. Javascript is an object-based language. Almost everything you encounter is an object. However, it is not a real Object-Oriented Programming (OOP) language, because its syntax does not contain class ).

Copy codeThe Code is as follows:
<Script type = "text/javascript">
// The object is a set of name/value pairs
Var browser = {// The object is enclosed by curly brackets.
Name: "Firefox ",
Kernel: "Gecko"
};
</Script>

Copy codeThe Code is as follows:
// Access the attributes of an object through the period (.) or []
Browser. name // "Firefox"
Browser ["kernel"] // "Gecko"

An object (objct) is a set of properties. Each property is composed of a "name/value pair". js also defines a special object-an array, it is an ordered set of numbered values. Js also defines a special object-function. A function is an object with executable code associated with it. It calls a function to execute the code and return the calculation result.

Clarify the concept:
In JS, "Object-based = Object-Oriented" 4. JS does not have a Class, but it has a new name called "prototype object", so "Class = prototype object"

Ii. Differences and relationships between classes (prototype objects) and objects (instances ### 

1. classes (prototype objects) are abstract, conceptual, and representative of a class of things.
2. objects are specific and actual, representing a specific thing.
3. A Class (prototype object) is a template of an object instance, and an object instance is a collection of classes.
A common misunderstanding is that the literal value of a number (literal) is not an object. This is because of an error in the JavaScript parser, which tries to resolve the vertex operator to a part of the floating-point numeric nominal value.

There are many workways to make the literal value of A number look like an object.

2. toString (); // The second vertex can be parsed normally.
2. toString (); // note the space before the dot
(2). toString (); // 2 is calculated first
Delete attributes

The only way to delete an attribute is to use the delete operator. Setting an attribute to undefined or null does not actually delete an attribute, but simply removes the association between attributes and values.

Three features of JavaScript object-oriented

Encapsulation: the internal implementation is not considered, but the function usage is considered only.
Inheritance: inherits new objects from existing objects.
Polymorphism: the so-called polymorphism refers to multiple states that reference different situations,
1. Encapsulation

Encapsulation is to classify the commonalities (including attributes and behaviors) of the same type of things into a class for convenient use. For example, the human stuff can be encapsulated in the following way:

Persons {
Age (attribute 1)
Height (attribute 2)
Gender (attribute 3)

Work (Behavior 1)
Walking (behavior 2)
Voice (Act 3)
}

Advantages of encapsulation:

Encapsulation protects the integrity of internal data;
Encapsulation makes object reconstruction easier;
Weaken the coupling between modules to improve the reusability of objects;
Helps avoid namespace conflicts;
Let's look at the following example:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var boy ={}; // create an empty object
Boy. name = "James"; // assign a value based on the properties of the prototype object
Boy. age = 12;

Var girl = {};
Girl. name = "Xiaohong ";
Girl. age = 10;
</Script>

This is the simplest encapsulation. Two attributes are encapsulated in an object. However, this method has two disadvantages: one is that if several instances are generated more, it will be very difficult to write; the other is that there is no way between the instance and the prototype, so we can see what the relationship is.

Constructor Mode

To solve the problem of generating instances from a prototype object, Javascript provides a Constructor mode.

The so-called "constructor" is actually a common function, but this variable is used internally. You can use the new operator to generate an instance for the constructor, and this variable is bound to the instance object.

For example, the prototype objects of boy and girl can be written as follows:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Person (name, age ){
This. name = name;
This. age = age;
}
</Script>

Now we can generate instance objects.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var boy = new Person ("James", "12 ");
Var girl = new Person ("Xiaohong", "10 ");

Alert (boy. name); // James
Alert (boy. age); // 12
</Script>

In this case, the Boy and girl will automatically contain a constructor attribute pointing to their constructor.
 
Copy codeThe Code is as follows:
Alert (boy. constructor = Person); // true

Alert (girl. constructor = Person); // true

The Prototype mode Javascript specifies that each constructor has a prototype attribute pointing to another object. All attributes and methods of this object will be inherited by the constructor instance.

This means that we can directly define the unchanged attributes and methods on the prototype object.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Person (name, age ){
This. name = name;
This. age = age;
}

Person. protype. type = "human ";

Person. protype. eat = function (){
Alert ("eat rice ");
}
</Script>

Then, generate the instance:

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var boy = new Person ("James", "12 ");
Var girl = new Person ("Xiaohong", "10 ");

Alert (boy. type); // human
Boy. eat (); // eat
</Script>

In this case, the type attribute and the eat () method of all instances are actually the same memory address, pointing to the prototype object, thus improving the running efficiency.

Alert (boy. eat = girl. eat); // true
The prototype attribute is a built-in attribute that specifies the extended constructor functions of the object.
The following code adds a new property size for the Animal constructor, which is the prototype property of the cat object. By using the prototype attribute, all objects that extend the Animal constructor function can access the size attribute.

Cat = new Animal ("feline", "meow", "walk/run ");
Cat. prototype. size = "fat ";
In this case, the size attribute of all Animal objects is "fat ". By default, the prototype is a new instance of the Object. Because it is still an Object, you can add new attributes to the Object. As if style is an object in javascript, you can add attributes after style.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
/* Define a Person class */
Function Person (_ name, _ age, _ salary ){
// Public attributes of the Person class. The public attributes of the class are defined as: "this. attribute name"
This. Name = _ name;
// The private property of the Person class. the private property of the class is defined as "var property name".
Var Age = _ age;
Var Salary = _ salary;

// Defines the public method (privileged method) of the Person class and the public method of the class.
Yes: "this. functionName = function () {...}"
This. Show = function (){
Alert ("Age =" + Age + "\ t" + "Salary =" + Salary); // The Private attributes of the category class in the public method are allowed.
}
</Script>

When an object looks for a property, it first traverses its own property. If it does not, it will continue to look for the object referenced by [[Prototype, if no Prototype exists, continue to [[Prototype]. [[Prototype] referenced objects, and so on until [[Prototype]. .... [[Prototype] is undefined (the [[Prototype] of the Object is undefined)

Simply put, you can use [[Prototype] of the object to save the reference to another object and use this reference to search for attributes. This is the Prototype chain.

Global window object

Any global function or variable in JavaScript is the property of window.
The self object is exactly the same as the window object. self is usually used to confirm that it is in the current form.

The main objects of window are as follows:

JavaScript document Object
JavaScript frames object
JavaScript history object
JavaScript location object
JavaScript navigator object
JavaScript screen Object
Several common methods

Valueof () method: returns the original value of the specified object.
The split () method splits the string into a string array and returns this array.
The indexOf () method returns the position of the first occurrence of a specified string value.
The substring () method is used to extract characters of a string between two specified subscripts.
The substr () method extracts a specified number of strings starting from the startPos position from the string.
The join () method is used to put all elements in the array into a string.
ArrayObject. join (separator)
The reverse () method is used to reverse the order of elements in the array.
The slice () method returns the selected element from an existing array.
Object literal

The object literal is used to create a process that contains a large number of attributes,

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var company = {
Name: "Microsoft ",
Ages: 39,
Employees: 99000,
CEO: "Nadella"
};
</Script>

Note that attributes and attribute values are separated by colons (:). Multiple Attributes are separated by commas. The object literal can also define a method. You only need to write the function on the property of the object. This is an anonymous function. To call this function, you only need to write its method name.

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var dog = {
Name: "husky ",
Age: 2,
Run: function (){
Return "123 ";
}
}
Alert (dog. run (); // If dog. run is input, the code of function
</Script>

Javascript Array

1. Array object

Array object: supports creating arrays of any data type.

Copy codeThe Code is as follows:
ArrayObj = new Array ()
ArrayObj = new Array ([size])
ArrayObj = new Array ([element0 [, element1 [,... [, elementN])

Definition: var arr = [2, 3, 45, 6]; var arr = new Array (2, 4, 5, 7)
There is no difference between the two definitions. [] has high performance because the code is short.

Use the array and object literal: var aTest = []; when creating an array, using the array literal is a good choice; similarly, the object literal can also be used to save space. The following two rows are equal, but the use of the object literal is shorter:

Var oTest = new Object; // try not to use
Var oTest ={}; // the best choice, or var 0 Test = [];
To achieve the best performance of array traversal, we recommend that you use a classic for loop.

Copy codeThe Code is as follows:
Var list = [1, 2, 3, 4, 5, ....... 100000000];
For (var I = 0, l = list. length; I <l; I ++ ){
Console. log (list [I]);
}

The preceding Code caches the length of an array through l = list. length.

Array Constructor

Since the Array constructor is ambiguous about how to process parameters, we always recommend that you use the Array literal syntax-[]-to create an Array.

The following code is confusing:

New Array (3, 4, 5); // result: [3, 4, 5]
New Array (3) // result: [], the Array length is 3
Avoid using arrays to create new arrays. We recommend that you use the literal Syntax of arrays. They are more short and concise, thus increasing the readability of the Code.

Attribute of Array

Three attributes of the Array: length, prototype, and constructor

1. length attribute

The Length attribute indicates the Length of the array, that is, the number of elements. Because the index of an array always starts from 0, the upper and lower limits of an array are: 0 and length-1. Unlike most other languages, the length attribute of the JavaScript array is variable, which requires special attention.

2. prototype attributes

Returns a reference to an object type prototype. The prototype attribute is common to objects.

For Array objects, the following example describes the purpose of the prototype attribute.
Add a method to the array object to return the maximum element value in the array. To do this, declare a function, add it to Array. prototype, and use it.

Copy codeThe Code is as follows:
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 is executed, y saves the maximum value in array x, or 6.

3. constructor attributes

The function that creates an object. Note: The constructor attribute is a member of all objects with prototype. They include all inherent JScript objects except Global and Math objects. The constructor attribute stores references to the functions used to construct a specific object instance.

For example:

Copy codeThe Code is as follows:
X = new String ("Hi ");
If (x. constructor = String) // process (the condition is true ).
// Or
Function MyFunc {
// Function body.
}

Y = new MyFunc;
If (y. constructor = MyFunc) // process (the condition is true ).

For arrays:

Y = new Array ();

Array method:

Attached is an array Mind Map:


Question about javascript Array object reference?

Big brother! The code is executed in order!
Section 1:
<Script export ahe = "javascript">
Var k = new Array (0); 1
Array [0] = 123; 2
Document. write (Array [0] + "<br>"); 3
Document. write (k [0]); 4
</Script>

1 k is null
2 Array [0] = 123; here are the postpaid values: k or null;
Print k or null;
The Code comes in order!

Section 2:
<Script language = "javascript">
Var kk = new Array (0); 1
Kk [0] = 123; 2
Var k = kk 3
Document. write (k [0]); 4
</Script>

1 kk is null
2 kk [0] = 123;
3 k = kk; kk you paid the value in 2nd sentences. Now you pay the value of kk to k.
4 k [0] = 123 so now k [0] is 123

Second question
Javascript has no data type
Var: What do you give him? What is his type!

If you write new kk, a new kk object is generated! Null is generated. Of course, nothing is displayed!

How are javascript Functions, objects, arrays, classes, and relationships?

If you really want to know more, just buy a book and read it.

In essence,. js does not have the concept of class.
Functions, objects, and arrays are all objects.
In addition, all JS objects are derived objects of the object (including functions and arrays)

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.