JavaScript objects and built-in objects of the inheritance tutorial (1)

Source: Internet
Author: User

I. Classes and objects

In the JavaScript world, class is the first concept to be clarified about object-oriented. Objects are defined by classes. Creating objects through classes is a familiar instantiation. However, in JavaScript, do not have a real class. The definition of an object is the object itself. While the ECMA-262 simply called this compromise method as the object of the regulator. For ease of understanding, I usually call the adjustment agent that plays the role of this class as a class.

2. built-in objects

1. Array class

Array is a very common data structure in js. Due to its flexibility and ease of use, the rational use of arrays can help us better implement the corresponding functions.

Let's take a look at the creation of an Array object.

First:

 
 
  1. var arr = new Array(10);  

This method is not very practical in actual use. Unlike many compilation languages, the js array length is variable, which not only enhances flexibility, we also have a better choice.

Second:

 
 
  1. var arr = new Array("one","two","three");  

The new method is usually used to create arrays. You can also use new Array () to create an empty Array object. In general, I recommend the following methods:

Third:

 
 
  1. var arr = ["one","two","three"];  

Creating an array object using the array literal is not only simple and easy to read, but also almost equivalent to creating an array object using the new method. There are many useful methods for array objects. Let's take a look at the powerful functions of this array object.

The first thing to introduce is the push method. Anyone who has learned the data structure knows what push means. That's right, his appearance enables the array to implement the data structure of the stack (along with the pop method at the same time ). The push method helps us compact the addition of array elements. The array in js is variable in length, so we can add elements. Since arr [length] = newValue; can be used to add a new element to arr and place it at the end of the array. A better way is to use the push method. How about arr. push (newValue); it is much easier to use it to add new values through the array length. Note the following. See the following code:

 
 
  1. var arr = [];   
  2. arr[4] = 5;   
  3. alert(arr.length == 5);   
  4. alert(arr); //alert : ,,,,5  

When we need to assign the specified value to the specified array location, this assignment is very useful, for example, when it is used for packing and sorting.

The pop method returns the last element of the array and outputs the stack.

 
 
  1. var arr = [1,2,3,4,5];   
  2. var ele = arr.pop();   
  3. alert(ele == 5);   
  4. alert(arr.length == 4); 

The toString and valueOf methods of the array objects are rewritten in a more user-friendly manner. The implementation of this method is to call the toString method for each item, and then use commas (,) to connect each item. So:

 
 
  1. var arr = [1,2,3,4,5];   
  2. alert(arr);//output:1,2,3,4,5   

The toLocaleString method is not described in detail here. Its effect is similar to that of the toString method, but each item calls the toLocateString method.

If you want to use personalized delimiters to display array elements, the join method may be more suitable. For example:

 
 
  1. Var city = ["Shanghai", "Beijing", "Tianjin", "Chongqing", "Shenzhen"];
  2. Alert (city. join ("|"); // output: Shanghai | Beijing | Tianjin | Chongqing | Shenzhen

Therefore, join converts an array element into a string. When introducing strings, we will see the use of the join method again.

The concat and slice methods are a pair of easy-to-use methods. The special feature of these two methods is that the String object also has them. When we want to add multiple array elements to an array, using push may seem redundant and complex, and it will make coding less interesting. Fortunately, we have the concat method, which adds its parameters to the array element in order. For example:

 
 
  1. var arr = [1,2,3,4,5];   
  2. arr = arr.concat(6,7,8,9);   
  3. alert(arr.length == 9);    

Note: concat does not modify the array object itself, but merges array elements with the array elements of the concat method and returns the results. Therefore, you must assign values to the array elements.

The slice Method returns a sub-array from the array object. This sub-array is from the position indicated by the first parameter of the slice method to the position indicated by the second parameter. This is a semi-open and semi-closed interval [a, B ). For example:

 
 
  1. var arr = [1,2,3,4,5];   
  2. var arr1 = arr.slice(1,3);   
  3. alert(arr1); //output:2,3   
  4. alert(arr); //output:1,2,3,4,5 

Well, the slice and concat methods are not modifying the array object itself. At the same time, parameter 1 and 3 represent the subarray of the semi-open and semi-closed intervals from position 1 to position 3.

I have discussed the stack operations of the back-in-first-out mode. Now let's take a look at the operations of the first-in-first-out mode. There is no problem in using the push method for columns. Is shift, which deletes the first element of the array object and returns:

 
 
  1. var arr = [1,2,3,4,5];   
  2. var ele = arr.shift();   
  3. alert(ele); //output:1   
  4. alert(arr.length);//output:4 

Another method is unshift, which inserts the new element into the first entry of the array object. Its function is the opposite of shift.

The sort method is flexible and can be used to sort array elements in any way you want. Because the sort method receives an anonymous function (in fact, it can also receive a non-Anonymous function, but it is generally not recommended to create such a name function for this purpose unless the function can be reused) as a condition for sorting. For example:

 
 
  1. Object.prototype.toString = function(){   
  2. var str = '';   
  3. for(var item in this) {   
  4. str += item + ":" + this[item] + ",";   
  5. }   
  6. return str.length?str.substr(0,str.length-1):str;   
  7. };   
  8. var arr = [{key:3,value:"three"},  
  9. {key:1,value:"one"},{key:2,value:"two"}];   
  10. arr.sort(function(a,b){   
  11. return a.key - b.key;   
  12. });   
  13. alert(arr);  
  14. //output:key:1,value:one,key:2,value:two,key:3,value:three   

We will not tangle with the Object. prototype. toString method first. It is about traversing the Object so that it can be output as a key-Value Pair Format String, which will be mentioned again when introducing the prototype chain. We can see that the sort method uses this anonymous method to sort by key attribute. Let's take a look at this anonymous method.

 
 
  1. function(a,b) {   
  2. return a.key - b.key;   
  3. };   

As you can see, this method receives two parameters, compares the parameter itself or an attribute, and returns the comparison result. The correspondence between the comparison result and the sorting result is as follows:

If paramA-paramB> 0, return is positive, B is placed before.

If paramA-paramB <0, return is negative, B is placed behind.

If paramA-paramB = 0 and return 0, the order remains unchanged.

The above implementation is ordered, so what about reverse order? Yes, return paramB-paramA;

The reverse method can reverse an array object. Like the sort method, it modifies the order of elements in the array object.

Finally, let's look at the splice method, which is the method to replace and delete elements of array objects. There are different implementation results based on parameter changes. Splice (pos, count [, insertParams]); The pos parameter is the position of the first item for deleting an element, and the count parameter is the number of deleted elements, if the value is 0, it will not be deleted (if this method is not deleted, do not worry, look down). insertParams is the parameter list, which is the set of elements to be inserted. The insert position is pos. Then there are the following situations.

1. When insertParams is ignored, this method deletes array elements.

2. When the count parameter is 0, this method only inserts insertParams into the pos position.

3. When the count parameter is not 0 and insertParams is not ignored, this method deletes the count elements starting from the pos position and replaces the insertParams parameter set.

2. Math class

We have spent a lot of time introducing array classes. I want to emphasize that this class is just to introduce a name that is easily imposed on it. In fact, they are just objects. Rather than the real class.

Math classes are relatively narrow in scope, because Math is a class of mathematical computing, rather than a Data Structure class. However, we also see Math. random and various methods to get integers. So we may take some time to look at them, but if you are not very interested in this, you can jump to the next section after reading the random method, and then turn to the manual later.

Math is usually a "static" class, because no one will instantiate a Math object, but directly use its "static" method. Some materials are called Math objects directly, here we may call it a "static" class.

First, I must introduce the random method, because it is often used and useful. It is always indispensable to create random events. It is also useful to prevent caching. Math. the Return Value of the random method is an open floating point number (0, 1) between 0 and 1. It is very simple to use. The only thing to note is that, we need to be cautious when filtering floor and ceil methods in order to perform an integer. The former indirectly converts random to the open interval after the anterior closure, while the latter is the closed interval after the former. If we need a random number ranging from 1 to, there are two common solutions:

Method 1:

 
 
  1. Math.ceil(Math.random*100);  

Method 2:

 
 
  1. Math.floor(Math.random*100)+1;  

The ceil method and the floor method are both mathematical methods used to get an integer. According to the meaning of a word, we can understand that the former is rounded up, while the latter is rounded down.

When we randomly select an array element from a continuous array object, we can use random to easily help us select:

 
 
  1. ["ipad","iphone","ipod touch","ipod nano","macbook"]  
  2. [Math.ceil(Math.random()*4)]; 

In this example, I directly use the array literal. At first, you may find it confusing or difficult to understand, when you go deeper, you will find that JavaScript is so convenient, concise, and flexible.

We have introduced the rounding of the ceil and floor methods. When we want to get close to the house, we can use Math. round method, which is used to obtain the rounded value according to the number. For example, Math. round (5.4) returns 5. If Math. round (5.5) is used, the answer is 6 instead of 5. You need to know about this. Okay, I admit it's true, but I know what's wrong with him.

What should we do when we want to get a small or large number from two numbers?

 
 
  1. if(a>b) {   
  2. return a;   
  3. } else {   
  4. return b;   
  5. }   

Let's worry about it. Math provides Math. max and Math. min methods to help us solve this problem.

Math also has a lot of "static" methods and attributes. I will not list them here. When we want to perform mathematical calculations, we may look up the manual.

3. String class

The usage frequency of a string object may not be as frequent as that of an array object. Why should I put it later? In fact, it is because we want to talk more about strings, scalable methods and tool functions are also more abundant. Let's take a look at the String class.

You can create a String object using the following methods:

Method 1:

 
 
  1. var str = new String("Hello World");  

Method 2:

 
 
  1. var str = String("Hello World");  

Method 3:

 
 
  1. var str = "Hello World";  

Like array objects, I recommend that you use the last method and string literal. Regarding whether there is a difference between the new operator and the new operator, Mr Zhou's blog has explained in detail. At the same time, if you keep reading it, you will also mention the new operator when introducing custom objects.

The String object has only one property length. It returns the length of the String. Here we must understand that JavaScript is unicode encoding, so Chinese characters and English characters are treated as one character length, this is because I have met more than one friend who asked this question on the forum. So what if we want to calculate Chinese characters as 2 characters in length? This brings us the first custom method.

 
 
  1. String.prototype.getLength = function(isSplit){   
  2. if(isSplit) {   
  3. return this.replace(/[^\u0000-\u00FF]/g,"tt").length;   
  4. }    
  5. else {   
  6. return this.length;   
  7. }   
  8. };  

This method uses a Boolean parameter. If it is true, it splits non-halfwidth characters, numbers, and English letters into two lengths for length, it does not modify the string object itself. If the value is false, the value of length is returned directly. Since the introduction method is not based on the Character arrangement order of the method, if it is used as a dictionary, I think w3school is more appropriate, because I will introduce it based on different roles and associations. OK. After introducing the length attribute, let's look at the string search.


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.