Basics of getting Started with JavaScript objects

Source: Internet
Author: User
Tags javascript array

What is an object
simply put, the object in the programming language is the simplification of things in the real world. For example, we are one object, but it is difficult for a programming language to fully describe a complex object. So we have to simplify, first of all, to simplify people into a combination of attributes and behavior, and then just keep a few attributes and behaviors that make sense to the program. For example, if we make a program that counts the height of a person in a certain school, then we can omit the behavior of the person in this program, leaving only the behavior and retaining the height attribute. In this way, we get the simplest object.

JavaScript string Object

Object's Properties
In fact, we've already used objects in the HTML DOM. For example, we know that a DOM node has some information, such as NodeName, NodeType, and so on, which is actually the property of the Node object. Let's take a string as an example to see the object's properties.

Properties of strings
var s = "I have a 7 character"; After defining the string of s, we have a string object that we can access its length attribute, which does not require our definition, is a built-in property. The way to access is as follows:

S.length Click on the button below to see the length of the string.

Alert (s.length)
Method of String Object (behavior)
Similarly, an object can have behavior, in the case of a string object, we can let the string return a position of letters or text, which is an act. You can use the buttons on the back to simply experience the various properties and methods of the string, which in the end will explain in detail how each method is used.

The code is as follows Copy Code
<script type= "Text/javascript" >var s = "I have a 7 character"; var str = "character" + "string"; Two strings added </script>
Alert (str)

Use the Length property of a string to be a string.


Alert (str.length)
Returns the character at the specified position using the Charat method.

Alert (Str.charat (0))
Alert (Str.charat (1))
The substring method intercepts a substring from a string.


Alert (str.substring (0,2))
IndexOf returns the position of the specified character or string in the string, and returns 1 if the character does not exist.


Alert (Str.indexof (' character ')
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 a section of JS code that uses the Date object. Click on a few buttons below to see the values of each variable.

The code is as follows Copy Code
<script type= "Text/javascript" > var today = new Date (); Creates a new Date object var todaystr = today.tostring ()//converts the date to a string var todaylocal = today.tolocalestring ();//Convert to local string var date = Tod Ay.getdate ()//Query Month date var day = Today.getday ()//query current week several var month = Today.getmonth ();//Query month var year = Today.getfullyear ( )//Query year </script>alert (TODAYSTR) alert (todaylocal) alert (date) alert (day) alert (month) alert (years)

Create a new Date object
We use the following statement to create a Date object.

var today = new Date (); After execution, the Date object created is saved in the Today variable.

Method of String Object (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.

The code is as follows Copy Code

<script type= "Text/javascript" >
function StartTime () {var today=new Date ();
var h=today.gethours ();
var m=today.getminutes ();

M=checktime (m); S=checktime (s);
document.getElementById (' clock '). innerhtml=h+ ": +m+": "+s;//re-execute every 500 milliseconds
Starttimet=settimeout (' StartTime () ', 500);}  function Checktime (i) {if (i<10) {i= "0" + i; }return i;} </script>


Array Objects

Create a JavaScript array

The code is as follows Copy Code

<script type= "Text/javascript" >
Stupid method
var arr = new Array ("HTML", "CSS", "JavaScript", "DOM");
A little more convenient way
var arr = ["HTML", "CSS", "JavaScript", "DOM"];
</script> like a String object, an array also has a length property, but it means that the array contains the number of elements. Click on the button below to see the length of the arr is 4.

Alert (arr.length)

Instance JavaScript array code
here is a simple use of the array of JS code, you can click on the back of the button to observe the values of each variable.

The code is as follows Copy Code

<script type= "Text/javascript" >
var arr = new Array ("HTML", "CSS", "JavaScript", "DOM");
var arr2 = new Array ("asp.net", "PHP", "Java ee", "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 subscript, starting from 0. You can click on the button below to view the elements at each location in the arr.

The code is as follows Copy Code
Alert (arr[0])//Position 0, which is the first element
Alert (Arr[1])
Alert (arr[2])
Alert (Arr[3])

As you can see from the code above, you get the Joinarr, Bigarr, Sortarr variables after calling several methods of the array, which are described later. You can look at the value of variables to guess how they work.


Mathematical Objects

Example JavaScript Math code

The code is as follows Copy Code

<script type= "Text/javascript" >
var num = Math.PI;
var rnum = Math.Round (num);/rounding

</script>

Let's go first. The value of Math.PI is stored in num, which is a built-in constant of JS, and you can click on the button below to view its value.

Alert (NUM)
Rnum is the value that num rounded.


Alert (Rnum)
The random method produces a random value between 0-1. Try clicking the buttons below a few more times to find that the numbers are changing.


Alert (Math.random ())


Function Object


In JavaScript, a function is also an object, and when we use the following statement to define a function, we actually define an object of type one.

The code is as follows Copy Code
function Add (a,b) {
return a+b;
}

To illustrate this issue, we can use the constructor of a function to define an add function:

The code is as follows Copy Code

<script type= "Text/javascript" >
var add = new Function (' A ', ' B ', ' return a+b ');
Alert (Add (1,2));</script>

The functions defined with this method are exactly the same as the functions above, but this syntax is cumbersome and generally not used.

Call method for function object
Call is a very useful way to control the running environment of a function, that is, the object within the control function that this is pointing to. The following example illustrates this problem:

function Whatsthis () {alert (this);} When we call the above function, we will see that this points to window, and experiment:

Whatsthis ()

But if you use call, we can control the direction of this within the function, for example:

Whatsthis.call (document) ()

The above code uses the call method of the function object to point this to document.

If the original function needs to accept parameters, such as the Add function, you can use the following form:

Add.call (document,1,2) that is, the first parameter of call is the object to bind to this, and 1 and 2 are the parameters that the original Add function needs to accept.

The Apply method of the (function) function object
The use of apply is basically consistent with call, except that the parameter is passed as an array or the Add function is an example:

Add.call (document,[1,2]) you can see that the two numeric parameters that the original function add needs to accept are passed into the apply in the form of an array.

(function) Function object's Caller property
function Whocalls () {alert (whocalls.caller);} function Shecalls () {whocalls ();} Whocalls () Shecalls ()

Using the caller property, you can see who called the current function. Note that only caller within the function body is valid.

(function) Function object's Arguments property
JavaScript functions can accept any number of parameters, so the number of arguments does not limit the ability of the function to be defined. In a function, we can use arguments to access the parameters of an incoming function, for example:

function Howmany () {var = arguments.length; alert (num); The}howmany function will output the number of parameters such as function, click on the following button to test.

Howmany (1,2,3,4) howmany (1,2,3,4,5,6,7,8)

function Arguments.callee
We already know that the function will have the arguments attribute, and Arguments.callee is the currently executing functions, for example:

function WhoAmI () {alert (Arguments.callee);} WhoAmI ()

Performing the above function displays the source code for the current function. Of course, we can call callee again, which is primarily 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.