Introduction to the JavaScript language and simple examples

Source: Internet
Author: User
Tags access properties natural logarithm

The language is Object-Based instead of object-oriented ). It is an object-based language mainly because it does not provide many functions related to object-oriented languages, such as abstraction, inheritance, and overloading. Instead, the complex objects created by other languages are unified to form a very powerful object system.
Although JavaScript is an object-based language, it still has some basic object-oriented features. It can create its own objects as needed to further expand the application scope of JavaScript and enhance the compilation of powerful Web documents.

I. Basic object knowledge
1. Basic Object Structure
Objects in JavaScript are composed of two basic elements: properties and methods. The former is the unit of information loading in the process of implementing the actions required by the object, which is associated with the variable. The latter means that the object can be executed according to the intent of the designer, it is connected to a specific function.

2. Ways to reference objects
To truly use an object, you can use the following methods:
O references JavaScript internal objects;
O provided by the browser environment;
O create a new object.
This means that an object must exist before it is referenced. Otherwise, the reference will be meaningless and an error message will appear. From the above, we can see that JavaScript reference objects can be obtained in three ways. You can either create a new object or use an existing object.

3. Object operation statements
JavaScript is not a pure object-oriented language. It has many functions that provide object-oriented language. Therefore, JavaScript designers choose it as an "Object-based" rather than an object-oriented language, javaScript provides several statements, keywords, and operators used to operate objects.
(1) For... in statement
The format is as follows:
For (Object Property name in known object name)
Note:
O this statement is used to control the cycle of operations on all attributes of known objects. It repeatedly places all the attributes of a known object to a variable instead of a counter.
O the statement can be operated without knowing the number of attributes in the object.
For example, the following functions show the content in the array:
Function showData (object)
For (var X = 0; X <30; X ++)
Document. write (object [I]);

This function accesses the attributes of each object through the ordered values of the array subscript. To use this function, you must first know the lower mark value of the array. Otherwise, an error occurs if the value is out of the range. For the For... in statement, you do not need to know the number of Object Attributes at all. See the following:
Function showData (object)
For (var prop in object)
Document. write (object [prop]);

When using this function, in the loop body, For automatically retrieves the attributes until the end of the function.
(2) with statement
This statement means that in the statement body, any reference to the variable is considered as the attribute of this object to save some code.
With object {
...}
All the statements in curly brackets after the with statement are in the scope of the object.
(3) this keyword
This is the current reference. In JavaScript, because the object reference is multi-level and multi-faceted, the reference of an object usually needs to be referenced by another object, another object may reference another object, which may cause confusion. In the end, you do not know the object currently referenced, therefore, JavaScript provides a statement to specify the current object for the object.
(4) New operator
Although the object functions in JavaScript are already very powerful. But what's more powerful is that designers can create their own objects as needed to meet a specific requirement. You can use the New operator to create a New object. The created object uses the following format:
Newobject = NEW Object (Parameters table );
Newobject: the object is an existing object, the parameters table parameter table, and new is a command statement in JavaScript.
For example, create a new date object.
NewData = New Data ()
Birthday = New Data (December 12.1998)
Then NewData and birthday can be used as a new date object.
 
4. Object attribute reference
Object attribute reference can be implemented in one of the following three methods:
(1) Use the dot (.) Operator
University. Name = "Yunnan Province"
University. city = "Kunming"
University. Date = "1999"

The university is an existing object. Name, City, and Date are its three attributes, and they are assigned values through operations.
(2) reference through object subscript
University [0] = "Yunnan"
University [1] = "Kunming City"
University [2] = "1999"

You can use cyclic operations to obtain the value of an access attribute in the form of an array.
Function showunievsity (object)
For (var j = 0; j <2; j ++)
Document. write (object [j])

If you use For... in, you can achieve this without knowing the number of its attributes:
Function showmy (object)
For (var prop in this)
Docament. write (this [prop]);

(3) implemented in the form of strings
University ["Name"] = "Yunnan"
University ["City"] = "Kunming City"
University ["Date"] = "1999"


5. Reference of object Methods
The reference of object methods in JavaScript is very simple.
ObjectName. methods ()
In fact, the methods () = FunctionName method is essentially a function. If you reference the showmy () method in the university object, you can use:
Document. write (university. showmy ())
Or: document. write (university)
For example, reference the cos () method in the internal object of math.
Then:
With (math)
Document. write (cos (35 ));
Document. write (cos (80 ));
If with is not used, the reference is more complex:
Document. write (Math. cos (35 ))
Document. write (math. sin (80 ))
 
Ii. attributes and methods of common objects
JavaScript provides us with some very useful internal objects and methods. You do not need to use scripts to implement these functions. This is the real purpose of object-based programming.
In JavaScript, three methods are provided: string, math, and Date. This provides very favorable conditions for programmers to quickly develop powerful script programs.

1. Common internal objects
In JavaScript, object attributes and methods are referenced in two situations: one is that the object is a static object, that is, you do not need to create an instance for the object when referencing its properties or methods. The other object must create an instance for the object or method that references the object, that is, this object is a dynamic object.
References to JavaScript internal objects are closely centered around their attributes and methods. Therefore, it is of great significance to understand and understand the static nature of objects in JavaScript.

1) String object
O string object: internal static.
O you can use the (.) operator to access properties and methods.
O basic format: objectName. prop/methods
(1) attributes of string objects
This object has only one attribute, that is, length. It indicates the number of characters in the string, including all characters.
Example:
Mytest = "This is a JavaScript"
Mystringlength = mytest. length
Finally, mystringlength returns the length of the mytest string to 20.
(2) method of String object
There are 19 methods for string objects. It is mainly used for character string display on the Web page, font size, font color, character search, and Case conversion of characters.
The main method is as follows:
O anchor (): This method creates the same anchor tag as in the Html document. Use anchor as in Html (A Name =. Access in the following format: string. anchor (anchorName ).
O how to control character display
Big font, Italics (), Italics (), bold (), bold (), blink (), small (), fixed () fixed highlight display, fontsize (size) control font size, etc.
O fontcolor method; fontcolor (color)
O string case-insensitive Conversion
ToLowerCase ()-lower case conversion, and toUpperCase () upper case conversion. The following code converts a given string to uppercase or lowercase:
String = stringValue. toUpperCase and string = stringValue. toLowerCase.
O character search: indexOf [charactor, fromIndex]
Search for the location where the charactor first appears from the specified formIndtx position.
Returns a part of the string: substring (start, end)
All characters starting from start to end are returned.
 
2) math object of arithmetic functions
Function: provides some self-reported operations except addition, subtraction, multiplication, and division. Such as logarithm and square root.
Static: static object
(1) main attributes
Math provides six attributes, they are often used in mathematics E constant, base 10 natural logarithm LN10, base 2 natural logarithm LN2, 3.14159 PI, 1/2 square root SQRT1-2, the square root of 2 is SQRT2.
(2) Main Methods
Absolute Value: abs ()
Sine Cosine: sin (), cos ()
Arcsin arccosine: asin (), acos ()
Tangent arc tangent: tan (), atan ()
Round: round ()
Square Root: sqrt ()
Pow (base, exponent)
...
3) Date and Time object
Function: provides an object related to date and time.
Static: Dynamic. You must use the New operator to create an instance. Example:
MyDate = New Date ()
The Date object does not provide direct access attributes. Only date and time can be obtained and set.
Start Date: 00:00:00, January 1, January 1, 1770.
1. method for obtaining the date
GetYear (): returns the number of years.
GetMonth (): returns the number of the current month.
GetDate (): returns the number of the current day.
GetDay (): returns the day of the week.
GetHours (): returned hours
GetMintes (: returns the number of minutes
GetSeconds (): returns the number of seconds.
GetTime (): returns the number of milliseconds.
(2) set the date and time:
SetYear (); set year
SetDate (): set the number of the current month
SetMonth (): set the number of copies in the current month
SetHours (): set the number of hours
SetMintes (): set the number of minutes
SetSeconds (): set the number of seconds
SetTime (): set the number of milliseconds
...
2. system functions in JavaScript
System functions in JavaScript are also called internal methods. It provides system functions unrelated to any object. Using these functions does not require creating any instances and can be used directly.
1. Return the value in the string expression:
Method Name: eval (string expression), for example:
Test = eval ("8 + 9 + 5/2 ");
2. Return the string ASCI:
Method Name: unEscape (string)
3. encoding of returned characters:
Method Name: escape (character)
4. Return real numbers:
ParseFloat (floustring );
5. Return the numbers of different hexadecimal values:
ParseInt (numbestring, rad. X)
Here, radix is the number base, and the number of numbs strings
 
Iii. Examples
The following is a JavaScript document for clock display. Many functions are used in this document.
Test4_1.htm
<Html>
<Head>
<Style TYPE = "text/css">
<Style>
</Style>
<Title> clock </title>
<Script LANGUAGE = "JavaScript">
Function showClock (){
}
Function hideClock (){
}
Var timerID = null
Var timerRunning = false
Function stopClock (){
If (timerRunning)
ClearTimeout (timerID );
TimerRunning = false
Document. clock. face. value = "";
}
Function showTime (){
Var now = new Date ();
Var year = now. getYear ();
Var month = now. getMonth () + 1;
Var date = now. getDate ();
Var hours = now. getHours ();
Var mins = now. getMinutes ();
Var secs = now. getSeconds ();
Var timeVal = "";
TimeVal + = (hours <= 12 )? Hours: hours-12 );
TimeVal + = (mins <10 )? ": 0": ":") + mins;
TimeVal + = (secs <= 10 )? ": 0": ":") + secs;
TimeVal + = (hours <12 )? "AM": "PM ");
TimeVal + = (month <10 )? "On 0": "on") + month + "-";
TimeVal + = date + "-" + year;
Document. clock. face. value = timeVal;
TimerID = setTimeout ("showTime ()", 1000 );
TimerRunning = true
}
Function startClock (){
StopClock ();
ShowTime ();
}
 
Function windowOpener (indexnum ){
Var loadpos = "date.html" + "#" + indexnum;
ControlWindow = window. open (loadpos, "date", "toolbar = no, location = no,
Directories = no, status = no, menubar = no, scrollbars = yes, resizable = yes,
Width = 620, height = 400 ");
}
</Script>
</Head>
<Body onLoad = "startClock ()">
<P align = "center"> <big> <span style = "background-color: rgb (45, 45, 45)">
<Font face = "Arial"> form </font> <font face = ""> clock </font>
</Span> </big> </p>
<P align = "center"> </p>
<Div align = "center"> <center>
<Table border = "0" cellspacing = "0" cellpadding = "0">
<Tr>
<Td width = "100%"> <form NAME = "clock" onSubmit = "0">
<Div align = "center"> <center> <p> <input TYPE = "text" NAME = "face" size = "20"
VALUE style = "background-color: rgb (192,192,192)"> </p>
</Center> </div>
</Form>
</Td>
</Tr>
</Table>
</Center> </div>
</Body>
</Html>

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.