Você está na página 1de 20

JavaScript Objects

Everything is an Object In JavaScript almost everything is an object. Even primitive data types (except null and undefined) can be treated as objects.

Booleans can be objects or primitive data treated as objects Numbers can be objects or primitive data treated as objects Strings are also objects or primitive data treated as objects Dates are always objects Maths and Regular Expressions are always objects Arrays are always objects Even functions are always objects

JavaScript Objects
An object is just a special kind of data, with properties and methods. Accessing Object Properties Properties are the values associated with an object. The syntax for accessing the property of an object is: objectName.propertyName This example uses the length property of the String object to find the length of a string: var message="Hello World!"; var x=message.length; The value of x, after execution of the code above will be: 12

Accessing Objects Methods


Methods are the actions that can be performed on objects. You can call a method with the following syntax: objectName.methodName()

This example uses the toUpperCase() method of the String object, to convert a text to uppercase: var message="Hello world!"; var x=message.toUpperCase(); The value of x, after execution of the code above will be: HELLO WORLD!

Creating JavaScript Objects


With JavaScript you can define and create your own objects.There are 2 different ways to create a new object:

1. Define and create a direct instance of an object. 2. Use a function to define an object, then create new object instances.

Creating a Direct Instance


This example creates a new instance of an object, and adds four properties to it: Example person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";

Using an Object Constructor


This example uses a function to construct the object: Example function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }

Creating JavaScript Object Instances


Once you have a object constructor, you can create new instances of the object, like this: var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green");

Adding Properties to JavaScript Objects


You can add new properties to an existing object by simply giving it a value. Assume that the personObj already exists - you can give it new properties named firstname, lastname, age, and eyecolor as follows: person.firstname="John"; person.lastname="Doe"; person.age=30; person.eyecolor="blue"; x=person.firstname; The value of x, after execution of the code above will be: John

Adding Methods to JavaScript Objects


Methods are just functions attached to objects. Defining methods to an object is done inside the constructor function: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName; function changeName(name) { this.lastname=name;} } The changeName() function assigns the value of name to the person's lastname property.

Now You Can Try: myMother.changeName("Doe");

JavaScript Classes
JavaScript is an object oriented language, but JavaScript does not use classes. In JavaScript you dont define classes and create objects from these classes (as in most other object oriented languages). JavaScript is prototype based, not class based.

JavaScript for...in Loop


The JavaScript for...in statement loops through the properties of an object. Syntax for (variable in object) { code to be executed } Note: The block of code inside of the for...in loop will be executed once for each property. Example Looping through the properties of an object: Example var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; }

JavaScript String Object


The String object is used for storing and manipulating text.

JavaScript Strings A string simply stores a series of characters like "John Doe".A string can be any text inside quotes. You can use single or double quotes: Example var carname="Volvo XC60"; var carname='Volvo XC60'; You can access each character in a string with its position (index): Example var character=carname[7]; String indexes are zero-based, which means the first character is [0], the second is [1], and so on. You can use quotes inside a string, as long as they don't match the quotes surrounding the string: Example var answer="It's alright"; var answer="He is called 'Johnny'"; var answer='He is called "Johnny"'; Or you can put quotes inside a string by using the \ escape character: Example var answer='It\'s alright'; var answer="He is called \"Johnny\"";

String Length
The length of a string (a string object) is found in the built in property length: Example var txt="Hello World!"; document.write(txt.length); var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.write(txt.length);

Finding a String in a String The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string: Example var str="Hello world, welcome to the universe."; var n=str.indexOf("welcome"); The method returns -1 if the specified text is not found. The lastIndexOf() method starts searching at the end of the string instead of at the beginning. Matching Content The match() method can be used to search for a matching content in a string: Example var str="Hello world!"; document.write(str.match("world") + "<br>"); document.write(str.match("World") + "<br>"); document.write(str.match("world!")); Replacing Content The replace() method replaces a specified value with another value in a string. Example str="Please visit Microsoft!" var n=str.replace("Microsoft","W3Schools"); Upper Case and Lower Case A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase(): Example var txt="Hello World!"; // String var txt1=txt.toUpperCase(); // txt1 is txt converted to upper var txt2=txt.toLowerCase(); // txt2 is txt converted to lower

Convert a String to an Array A string is converted to an array with the built in method string.split(): Example txt="a,b,c,d,e" // String txt.split(","); // Split on commas txt.split(" "); // Split on spaces txt.split("|"); // Split on pipe Special Characters The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string. var txt="We are the so-called "Vikings" from the north."; document.write(txt); In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal: var txt="We are the so-called \"Vikings\" from the north."; document.write(txt); JavaScript will now output the proper text string: We are the so-called "Vikings" from the north. The table below lists other special characters that can be added to a text string with the backslash sign: Code
\' \" \\ \n \r

Outputs
single quote double quote backslash new line carriage return

\t \b \f

tab backspace form feed

Strings can be Strings or Objects


JavaScript strings can be primitive values created from literals, like var x = "John"; JavaScript strings can also be objects created with the new keyword, like var y = new String("John"); Example var x = "John"; var y = new String("John"); typeof(x) // returns String typeof(y) // returns Object Normally, because of some nasty side effects, you will not define strings as objects. Example var x = "John"; var y = new String("John"); (x === y) // is false because x is a string and y is an object. Note: Primitive values, like "John", cannot have properties or methods (because they are not objects). With JavaScript, all methods and properties of the string object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods or properties. String Properties and Methods Properties:

length prototype constructor

Methods:

charAt() charCodeAt() concat() fromCharCode() indexOf() lastIndexOf() match() replace() search() slice() split() substr() substring() toLowerCase() toUpperCase() valueOf()

JavaScript Date Object


The Date object is used to work with dates and times. Create a Date Object The Date object is used to work with dates and times. Date objects are created with the Date() constructor. There are four ways of initiating a date: new Date() // current date and time new Date(milliseconds) //milliseconds since 1970/01/01 new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) Most parameters above are optional. Not specifying, causes 0 to be passed in.

Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time. All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds. Some examples of initiating a date: var today = new Date() var d1 = new Date("October 13, 1975 11:13:00") var d2 = new Date(79,5,24) var d3 = new Date(79,5,24,11,33,0)

Set Dates
We can easily manipulate the date by using the methods available for the Date object. In the example below we set a Date object to a specific date (14th January 2010): var myDate=new Date(); myDate.setFullYear(2010,0,14); And in the following example we set a Date object to be 5 days into the future: var myDate=new Date(); myDate.setDate(myDate.getDate()+5); Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Compare Two Dates


The Date object is also used to compare two dates. The following example compares today's date with the 14th January 2100: var x=new Date(); x.setFullYear(2100,0,14); var today = new Date(); if (x>today) { alert("Today is before 14th January 2100");

} else { alert("Today is after 14th January 2100"); } JavaScript Array Object The Array object is used to store multiple values in a single variable. Create an array, and assign values to it: Example var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1="Saab"; var car2="Volvo"; var car3="BMW"; Create an Array An array can be created in three ways. The following code creates an Array object called myCars: 1: Regular: var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; 2: Condensed:

var myCars=new Array("Saab","Volvo","BMW"); 3: Literal: var myCars=["Saab","Volvo","BMW"]; Access an Array To an element in an array by referring to the index number.This statement access the value of the first element in myCars: var name=myCars[0]; This statement modifies the first element in myCars: myCars[0]="Opel"; You Can Have Different Objects in One Array All JavaScript variables are objects. Array elements are objects. Functions are objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: myArray[0]=Date.now; myArray[1]=myFunction; myArray[2]=myCars; Array Methods and Properties The Array object has predefined properties and methods: var x=myCars.length // the number of elements in myCars var y=myCars.indexOf("Volvo") // the index position of "Volvo" Create New Methods Prototype is a global constructor in JavaScript. It can construct new properties and methods for any JavaScript Objects. Example: Make a new Array method. Array.prototype.ucase=function() { for (i=0;i<this.length;i++)

{this[i]=this[i].toUpperCase();} }

JavaScript Event Handlers


An event handler executes a segment of a code based on certain events occurring within the application, such as onLoad, onClick. JavaScript event handers can be divided into two parts: interactive event handlers and non-interactive event handlers. An interactive event handler is the one that depends on the user interactivity with the form or the document. For example, onMouseOver is an interactive event handler because it depends on the users action with the mouse. On the other hand non-interactive event handler would be onLoad, because this event handler would automatically execute JavaScript code without the user's interactivity. Here are all the event handlers available in JavaScript: Event Handler onAbort onBlur onChange onClick onError onFocus onLoad onMouseOver onMouseOut onSelect onSubmit onUnload onAbort:
An onAbort event handler executes JavaScript code when the user aborts loading an image. <HTML> <TITLE>Example of onAbort Event Handler</TITLE> <HEAD> </HEAD> <BODY> <H3>Example of onAbort Event Handler</H3> <b>Stop the loading of this image and see what happens:</b><p> <IMG SRC="reaz.gif" onAbort="alert('You stopped the loading the image!')"> </BODY> </HTML>

Used In image select, text, text area select, text, textarea button, checkbox, radio, link, reset, submit, area image select, text, testarea windows, image link, area link, area text, textarea form window

Here, an alert() method is called using the onAbort event handler when the user aborts loading the image.

onBlur:
An onBlur event handler executes JavaScript code when input focus leaves the field of a text, textarea, or a select option. For windows, frames and framesets the event handler executes JavaScript code when the window loses focus. In windows you need to specify the event handler in the <BODY> attribute. For example: <BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'"> Note: On a Windows platform, the onBlur event does not work with <FRAMESET>.
<HTML> <TITLE>Example of onBlur Event Handler</TITLE> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function valid(form){ var input=0; input=document.myform.data.value; if (input<0){ alert("Please input a value that is less than 0"); } } </SCRIPT> </HEAD> <BODY> <H3> Example of onBlur Event Handler</H3> Try inputting a value less than zero:<br> <form name="myform"> <input type="text" name="data" value="" size=10 onBlur="valid(this.form)"> </form> </BODY> </HTML>

In this example, 'data' is a text field. When a user attempts to leave the field, the onBlur event handler calls the valid() function to confirm that 'data' has a legal value. Note that the keyword this is used to refer to the current object. onChange: The onChange event handler executes JavaScript code when input focus exits the field after the user modifies its text.
<HTML> <TITLE>Example of onChange Event Handler</TITLE> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function valid(form){ var input=0; input=document.myform.data.value; alert("You have changed the value from 10 to " + input ); }

</SCRIPT> </HEAD> <BODY> <H3>Example of onChange Event Handler</H3> Try changing the value from 10 to something else:<br> <form name="myform"> <input type="text" name="data" value="10" size=10 onChange="valid(this.form)"> </form> </BODY> </HTML>

In this example, 'data' is a text field. When a user attempts to leave the field after a change of the original value, the onChange event handler calls the valid() function which alerts the user about value that has been inputted.

onClick:
In an onClick event handler, JavaScript function is called when an object in a button (regular, radio, reset and submit) is clicked, a link is pushed, a checkbox is checked or an image map area is selected. Except for the regular button and the area, the onClick event handler can return false to cancel the action. For example: <INPUT TYPE="submit" NAME="mysubmit" VALUE="Submit" onClick="return confirm(`Are you sure you want to submit the form?')"> Note: On Windows platform, the onClick event handler does not work with reset buttons.
<HTML> <TITLE>Example of onClick Event Handler</TITLE> <HEAD> <SCRIPT LANGUAGE="JavaScript"> function valid(form){ var input=0; input=document.myform.data.value; alert("Hello " + input + " ! Welcome..."); } </SCRIPT> </HEAD> <BODY> <H3> Example of onClick Event Handler </H3> Click on the button after inputting your name into the text box:<br> <form name="myform"> <input type="text" name="data" value="" size=10> <INPUT TYPE="button" VALUE="Click Here" onClick="valid(this.form)"> </form> </BODY> </HTML>

In this example, when the user clicks the button "Click Here", the onClick event handler calls the function valid().

onError: An onError event handler executes JavaScript code when an error occurs while loading a document or an image. With onError event now you can turn off the standard JavaScript error messages and have your own function that will trace all the errors in the script. To disable all the standard JavaScript error messages, all you need to do is set window.onerror=null. To call a function when an error occurs all you need to do is this: onError="myerrorfunction()"
<HTML> <TITLE>Example of onError event handler</TITLE> <HEAD> <SCRIPT Language="JavaScript"> window.onerror = ErrorSetting var e_msg=""; var e_file=""; var e_line=""; document.form[8].value="myButton"; //This is the error function ErrorSetting(msg, file_loc, line_no) { e_msg=msg; e_file=file_loc; e_line=line_no; return true; } function display() { var error_d = "Error in file: " + e_file + "\nline number:" + e_line + "\nMessage:" + e_msg; alert("Error Window:\n"+error_d); } </SCRIPT> </HEAD> <BODY> <h3> Example of onError event handler </h3> <form> <input type="button" value="Show the error" onClick="display()"></form> </body> </HTML>

Notice that the function ErrorSetting() takes three arguments: message text, URL and Line number of the error line. So all we did was invoke the function when an error occured and set these values to three different variables. Finally, we displayed the values via an alert method. Note: If you set the function ErrorSetting() to False, the standard dialog will be seen.

onFocus: An onFocus event handler executes JavaScript code when input focus enters the field either by tabbing in or by clicking but not selecting input from the field. For windows, frames and framesets the event handler executes JavaScript code when the window gets focused. In windows you need to specify the event handler in the <BODY> attribute. For example: <BODY BGCOLOR="#ffffff" onFocus="document.bgcolor='#000000'"> Note: On a Windows platform, the onFocus event handler does not work with <FRAMESET>.
<HTML> <TITLE>Example of onFocus Event Handler</TITLE> <HEAD></HEAD> <BODY> <H3>Example of onFocus Event Handler</H3> Click your mouse in the text box:<br> <form name="myform"> <input type="text" name="data" value="" size=10 onFocus='alert("You focused the textbox!!")'> </form> </BODY> </HTML>

In the above example, when you put your mouse on the text box, an alert() message displays a message. onLoad: An onLoad event occurs when a window or image finishes loading. For windows, this event handler is specified in the BODY attribute of the window. In an image, the event handler will execute handler text when the image is loaded. For example:
<IMG NAME="myimage" SRC="http://rhoque.com/ad_rh.jpg" onLoad="alert('You loaded myimage')"> <HTML> <TITLE>Example of onLoad Event Handler</TITLE> <HEAD> <SCRIPT LANGUGE="JavaScript"> function hello(){ alert("Hello there...\nThis is an example of onLoad."); } </SCRIPT> </HEAD> <BODY onLoad="hello()"> <H3>Example of onLoad Event Handler</H3> </BODY> </HTML>

The example shows how the function hello() is called by using the onLoad event handler.

onMouseOver: JavaScript code is called when the mouse is placed over a specific link or an object or area from outside that object or area. For area object the event handler is specified with the <AREA> tag. For example:
<MAP NAME="mymap"> <AREA NAME="FirstArea" COORDS="0,0,49,25" HREF="mylink.html" onMouseOver="self.status='This will take you to mylink.html'; return true"> </MAP> <HTML> <TITLE>Example of onMouseOver Event Handler</TITLE> <HEAD> </HEAD> <BODY> <H3> Example of onMouseOver Event Handler </H3> Put your mouse over <A HREF="" onMouseOver="window.status='Hello! How are you?' ; return true;"> here</a> and look at the status bar (usually at the bottom of your browser window). </BODY> </HTML>

In the above example when you point your mouse to the link, the text "Hello! How are you?" appears on your window's status bar. onMouseOut: JavaScript code is called when the mouse leaves a specific link or an object or area from outside that object or area. For area object the event handler is specified with the <AREA> tag.
<HTML> <TITLE> Example of onMouseOut Event Handler </TITLE> <HEAD> </HEAD> <BODY> <H3> Example of onMouseOut Event Handler </H3> Put your mouse over <A HREF="" onMouseOut="window.status='You left the link!' ; return true;"> here</a> and then take the mouse pointer away. </BODY> </HTML> In the above example, after pointing your mouse and leaving the link , the text "You left the link!" appears on your window's staus bar.

onReset:
A onReset event handler executes JavaScript code when the user resets a form by clicking on the reset button. <HTML> <TITLE>Example of onReset Event Handler</TITLE> <HEAD></HEAD> <BODY>

<H3> Example of onReset Event Handler </H3> Please type something in the text box and press the reset button:<br> <form name="myform" onReset="alert('This will reset the form!')"> <input type="text" name="data" value="" size="20"> <input type="reset" Value="Reset Form" name="myreset"> </form> </BODY> </HTML> In the above example, when you push the button, "Reset Form" after typing something, the alert method displays the message, "This will reset the form!"

onSelect:
A onSelect event handler executes JavaScript code when the user selects some of the text within a text or textarea field. <HTML> <TITLE>Example of onSelect Event Handler</TITLE> <HEAD></HEAD> <BODY> <H3>Example of onSelect Event Handler</H3> Select the text from the text box:<br> <form name="myform"> <input type="text" name="data" value="Select This" size=20 onSelect="alert('This is an example of onSelect!!')"> </form> </BODY> </HTML> In the above example, when you try to select the text or part of the text, the alert method displays the message, "This is an example of onSelect!!".

onSubmit: An onSubmit event handler calls JavaScript code when the form is submitted.
<HTML> <TITLE> Example of onSubmit Event Handler </TITLE> <HEAD> </HEAD> <BODY> <H3>Example of onSubmit Event Handler </H3> Type your name and press the button<br> <form name="myform" onSubmit="alert('Thank you ' + myform.data.value +'!')"> <input type="text" name="data"> <input type="submit" name ="submit" value="Submit this form"> </form> </BODY> In this example, the onSubmit event handler calls an alert() function when the button "Sumbit this form" is pressed.

onUnload:
An onUnload event handler calls JavaScript code when a document is exited.

<HTML> <TITLE>Example 2.11</TITLE> <HEAD> <SCRIPT LANGUGE="JavaScript"> function goodbye(){ alert("Thanks for Visiting!"); } </SCRIPT> </HEAD> <BODY onUnLoad="goodbye()"> <H3>Example of onUnload event handler</H3> Look what happens when you try to leave this page... </BODY> </HTML>

In this example, the onUnload event handler calls the Goodbye() function as user exits a document. Note: You can also call JavaScript code via explicit event handler call. For example say you have a function called myfunction(). You could call this function like this: document.form.mybotton.onclick=myfunction Notice that you don't need to put () after the function and also the event handler has to be spelled out in lowercase.

Você também pode gostar