Basic Introduction to javascript object-oriented

Source: Internet
Author: User
Tags javascript array

What is an object?

To put it simply, the objects in programming languages are simplified for things in reality. For example, we are an object, but it is difficult for programming languages to fully describe such a complex object. Therefore, we must simplify the process. First, we should simplify people into a combination of attributes and actions, and then only keep the attributes and actions that are meaningful to the program. For example, if we develop a program to count the heights of people in a school, we can omit the human behaviors in this program and only keep the behaviors, only the height attribute is retained. In this way, we get the simplest object.

JavaScript string object

Object Attributes
In fact, we are already using objects in html dom. For example, we know that DOM nodes have some information, such as nodeName and nodeType, which are actually the attributes of node objects. The following uses a string as an example to check the attributes of an object.

String attributes
Var s = "I have a 7 character"; after defining the string s, we have a string object. We can access its length attribute (length ), this attribute does not need to be defined. It is a built-in attribute. The access method is as follows:

S. length click the button below to see the length of the string.

Alert (s. length)
String object method (behavior)
Similarly, an object can have behavior. Taking a String object as an example, we can let the string return letters or texts at a certain position. This is an action. You can use the buttons below to experience the attributes and methods of the string. This article will explain in detail how to use each method.

Copy codeThe Code is as follows: <script type = "text/javascript">
Var s = "I have 7 characters"; var str = "character" + "string"; // Add two strings
Alert (str)
</Script>

Use the length attribute of the string to set the length of the string.

Alert (str. length)
Use the charAt method to return the characters at the specified position.

Alert (str. charAt (0 ))
Alert (str. charAt (1 ))

The substring method truncates a substring from a string.

Alert (str. substring (0, 2 ))
IndexOf returns the position of the specified character or string in the string. If the character does not exist,-1 is returned.

Alert (str. indexOf ('delimiter ')
The lastIndexOf method returns the position of the last occurrence of a character in a string.

Date object

Instance JavaScript date Code
Let's take a look at the JS Code that uses the date object. Click the buttons below to view the values of each variable.

Copy codeThe Code is as follows: <script type = "text/javascript">
Var today = new Date (); // create a Date object
Var todayStr = today. toString (); // converts a date to a string.
Var todayLocal = today. toLocaleString (); // convert to a local string
Var date = today. getDate (); // query the current month date.
Var day = today. getDay (); // query the current day of the week
Var month = today. getMonth (); // query the month
Var year = today. getFullYear (); // query the year
Alert (todayStr );
Alert (todayLocal );
Alert (date );
Alert (day );
Alert (month );
Alert (year );
</Script>

Create a Date object
Use the following statement to create a Date object.

Var today = new Date (); after execution, the created Date object is saved in the today variable.

String object method (behavior)
JavaScript date object query (get) Method
JavaScript date object setting (set) Method
JavaScript date object conversion (to) Method
JavaScript Date object application instance-Clock Code
This code is transferred from w3schools.com.Copy codeThe Code is as follows: <script type = "text/javascript">
Function startTime () {var today = new Date ();
Var h = today. getHours ();
Var m = today. getMinutes ();
Var s = today. getSeconds (); // Add 0 to the front when the number is smaller than 10.
M = checkTime (m); s = checkTime (s );
Document. getElementById ('clock '). innerHTML = h + ":" + m + ":" + s; // execute the task again every 500 milliseconds.
StartTimet = setTimeout ('startTime ()', 500 );}
Function checkTime (I ){
If (I <10 ){
I = "0" + I;
}
Return I;
}
</Script>

Array object

Create a JavaScript ArrayCopy codeThe Code is as follows: <script type = "text/javascript">
// Stupid method
Var arr = new Array ("HTML", "CSS", "JavaScript", "DOM ");
// Easy-to-use method
Var arr = ["HTML", "CSS", "JavaScript", "DOM"];
Like a String object, an array also has a length attribute, but it means the number of elements contained in an array. Click the button below to see that the arr length is 4.
Alert (arr. length)
</Script>

Instance JavaScript Array code

Below is a simple JS code using arrays. You can click the button next to it to observe the values of each variable.Copy codeThe Code is as follows: <script type = "text/javascript">
Var arr = new Array ("HTML", "CSS", "JavaScript", "DOM ");
Var arr2 = new Array ("ASP. NET", "PHP", "J2EE", "Python", "Ruby ");
Var joinArr = arr. join ();
Var bigArr = arr. concat (arr2 );
Var sortArr = bigArr. sort ();
</Script>

Arr [n] returns the element at the specified position of the array. n is called a subscript and starts from 0. You can click the following button to view the elements in each location of arr.Copy codeThe Code is as follows: alert (arr [0]) // The position is 0, that is, the first element.
Alert (arr [1])
Alert (arr [2])
Alert (arr [3])

From the code above, we can see that after several methods of the array are called, the variables joinArr, bigArr, and sortArr are obtained. These methods will be detailed later. You can first observe the value of the variable to guess the role of these methods.

Mathematical object
JavaScript Math code example

Copy codeThe Code is as follows: <script type = "text/javascript">
Var num = Math. PI;
Var rNum = Math. round (num); // rounding
</Script>

First, save the value of Math. PI in num. This is a JS built-in constant. You can click the following button to view its value.
Alert (num)
RNum is the rounded value of num.

Alert (rNum)
The random method generates a random value between 0 and 1. Click the button several times to find that the number is constantly changing.

Alert (Math. random ())

Function object

In JavaScript, functions are also objects. When we use the following statements to define a Function, we actually define a Function-type object.Copy codeThe Code is as follows: function add (a, B ){
Return a + B;
}

To illustrate this problem, we can use the Function constructor to define an add Function:Copy codeThe Code is as follows: <script type = "text/javascript">
Var add = new Function ('A', 'B', 'Return a + B ');
Alert (add (1, 2 ));
</Script>

The functions defined using this method are exactly the same as the above functions, but this syntax is troublesome and generally not used.
Call method of the Function object
Call is a very useful method. It can control the runtime environment of a function, that is, the object that this points to inside the function. The following example illustrates the problem:
Function whatsThis () {alert (this);} when we call the above function, we will see that this points to the window. Experiment:
WhatsThis ()
However, if call is used, we can control the point of this in the function, for example:
WhatsThis. call (document )()
The code above uses the call method of the function object to direct this inside the function to the document.
If the original function needs to accept parameters, such as the add function, the following form can be used:
Add. call (document, 1, 2) That is to say, the first parameter of call is the object to be bound to this, and 1 and 2 are the parameters required by the original add function.
(Function) Function object apply Method
The usage of apply is basically the same as that of call, except that the parameters are transmitted in the form of arrays, or the add function is used as an example:
Add. call (document, [1, 2]). As you can see, the two numeric parameters to be accepted by the original function add are transmitted to apply in the form of an array.
(Function) caller attribute of the Function object
Function whocall() {alert (whocall. caller);} function shecall() {whocall();} whocall() shecall ()
You can use the caller attribute to find out who has called the current function. Note that caller is valid only within the function body.
(Function) the arguments attribute of the Function object
Javascript Functions can accept any number of parameters. Therefore, when defined, the number of parameters does not limit the function's capability. In a function, we can use arguments to access the parameters of the input function. For example:
Function howents () {var num = arguments. length; alert (num) ;}the howents function will output the number of parameters passed, such as the number of function parameters. Click the following button to test.
Howmany (,) howmany)
Function arguments. callee
We already know that the function will have the arguments attribute, while arguments. callee is the function currently being executed, for example:
Function whoAmI () {alert (arguments. callee);} whoAmI ()
The source code of the current function is displayed. Of course, we can call callee again, which is mainly used for anonymous function recursion.

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.